Apache POI 是創(chuàng)建和維護(hù)操作各種符合Office Open XML(OOXML)標(biāo)準(zhǔn)和微軟的OLE 2復(fù)合文檔格式(OLE2)的Java API。用它可以使用Java讀取和創(chuàng)建,修改MS Excel文件.而且,還可以使用Java讀取和創(chuàng)建MS Word和MSPowerPoint文件,。Apache POI 提供Java操作Excel解決方案(適用于Excel97-2008),。
簡單理解就是通過POI,,java可以與office建立聯(lián)系,。
本次項目實踐基于SSM框架,簡單封裝了Excel批量導(dǎo)入導(dǎo)出功能,,實現(xiàn)過程如下
1. maven導(dǎo)入java包:
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi-ooxml</artifactId>
- <version>3.5-FINAL</version>
- </dependency>
2. 建立Excel實體--ExcelBean
- /**
- *
- * @Description: 導(dǎo)入導(dǎo)出excel
- * @author haipeng
- * @date 2017年4月11日
- */
- public class ExcelBean implements java.io.Serializable {
- private String headTextName;//列頭(標(biāo)題)名
- private String propertyName;//對應(yīng)字段名
- private Integer cols;//合并單元格數(shù)
- private XSSFCellStyle cellStyle;
-
- public ExcelBean(){
-
- }
- public ExcelBean(String headTextName, String propertyName){
- this.headTextName = headTextName;
- this.propertyName = propertyName;
- }
-
- public ExcelBean(String headTextName, String propertyName, Integer cols) {
- super();
- this.headTextName = headTextName;
- this.propertyName = propertyName;
- this.cols = cols;
- }
-
- public String getHeadTextName() {
- return headTextName;
- }
-
- public void setHeadTextName(String headTextName) {
- this.headTextName = headTextName;
- }
-
- public String getPropertyName() {
- return propertyName;
- }
-
- public void setPropertyName(String propertyName) {
- this.propertyName = propertyName;
- }
-
- public Integer getCols() {
- return cols;
- }
-
- public void setCols(Integer cols) {
- this.cols = cols;
- }
-
- public XSSFCellStyle getCellStyle() {
- return cellStyle;
- }
-
- public void setCellStyle(XSSFCellStyle cellStyle) {
- this.cellStyle = cellStyle;
- }
- }
3. 封裝Excel工具類--ExcelUtils
- public class ExcelUtils {
- private final static String excel2003L =".xls"; //2003- 版本的excel
- private final static String excel2007U =".xlsx"; //2007+ 版本的excel
- /*************************************文件上傳****************************/
- public static List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
- List<List<Object>> list = null;
-
- //創(chuàng)建Excel工作薄
- Workbook work = getWorkbook(in,fileName);
- if(null == work){
- throw new Exception("創(chuàng)建Excel工作薄為空,!");
- }
- Sheet sheet = null;
- Row row = null;
- Cell cell = null;
-
- list = new ArrayList<List<Object>>();
- //遍歷Excel中所有的sheet
- for (int i = 0; i < work.getNumberOfSheets(); i++) {
- sheet = work.getSheetAt(i);
- if(sheet==null){continue;}
-
- //遍歷當(dāng)前sheet中的所有行
- for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
- row = sheet.getRow(j);
- if(row==null||row.getFirstCellNum()==j){continue;}
-
- //遍歷所有的列
- List<Object> li = new ArrayList<Object>();
- for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
- cell = row.getCell(y);
- li.add(getCellValue(cell));
- }
- list.add(li);
- }
- }
- // work.close();
- return list;
- }
-
- /**
- * 描述:根據(jù)文件后綴,自適應(yīng)上傳文件的版本
- * @param inStr,fileName
- * @return
- * @throws Exception
- */
- public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
- Workbook wb = null;
- String fileType = fileName.substring(fileName.lastIndexOf("."));
- if(excel2003L.equals(fileType)){
- wb = new HSSFWorkbook(inStr); //2003-
- }else if(excel2007U.equals(fileType)){
- wb = new XSSFWorkbook(inStr); //2007+
- }else{
- throw new Exception("解析的文件格式有誤,!");
- }
- return wb;
- }
-
- /**
- * 描述:對表格中數(shù)值進(jìn)行格式化
- * @param cell
- * @return
- */
- public static Object getCellValue(Cell cell){
- Object value = null;
- DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
- SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
- DecimalFormat df2 = new DecimalFormat("0.00"); //格式化數(shù)字
-
- switch (cell.getCellType()) {
- case Cell.CELL_TYPE_STRING:
- value = cell.getRichStringCellValue().getString();
- break;
- case Cell.CELL_TYPE_NUMERIC:
- if("General".equals(cell.getCellStyle().getDataFormatString())){
- value = df.format(cell.getNumericCellValue());
- }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
- value = sdf.format(cell.getDateCellValue());
- }else{
- value = df2.format(cell.getNumericCellValue());
- }
- break;
- case Cell.CELL_TYPE_BOOLEAN:
- value = cell.getBooleanCellValue();
- break;
- case Cell.CELL_TYPE_BLANK:
- value = "";
- break;
- default:
- break;
- }
- return value;
- }
- /****************************************上傳結(jié)束***************************************
- /**
- * 多列頭創(chuàng)建EXCEL
- *
- * @param sheetName 工作簿名稱
- * @param clazz 數(shù)據(jù)源model類型
- * @param objs excel標(biāo)題列以及對應(yīng)model字段名
- * @param map 標(biāo)題列行數(shù)以及cell字體樣式
- * @return
- * @throws IllegalArgumentException
- * @throws IllegalAccessException
- * @throws InvocationTargetException
- * @throws ClassNotFoundException
- * @throws IntrospectionException
- * @throws ParseException
- */
- public static XSSFWorkbook createExcelFile(Class clazz, List objs,Map<Integer, List<ExcelBean>> map,String sheetName) throws IllegalArgumentException,IllegalAccessException,
- InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException{
- // 創(chuàng)建新的Excel 工作簿
- XSSFWorkbook workbook = new XSSFWorkbook();
- // 在Excel工作簿中建一工作表,,其名為缺省值, 也可以指定Sheet名稱
- XSSFSheet sheet = workbook.createSheet(sheetName);
- // 以下為excel的字體樣式以及excel的標(biāo)題與內(nèi)容的創(chuàng)建,下面會具體分析;
- createFont(workbook);//字體樣式
- createTableHeader(sheet, map);//創(chuàng)建標(biāo)題(頭)
- createTableRows(sheet, map, objs, clazz);//創(chuàng)建內(nèi)容
- return workbook;
- }
- private static XSSFCellStyle fontStyle;
- private static XSSFCellStyle fontStyle2;
- public static void createFont(XSSFWorkbook workbook) {
- // 表頭
- fontStyle = workbook.createCellStyle();
- XSSFFont font1 = workbook.createFont();
- font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
- font1.setFontName("黑體");
- font1.setFontHeightInPoints((short) 14);// 設(shè)置字體大小
- fontStyle.setFont(font1);
- fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下邊框
- fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左邊框
- fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上邊框
- fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右邊框
- fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
-
- // 內(nèi)容
- fontStyle2=workbook.createCellStyle();
- XSSFFont font2 = workbook.createFont();
- font2.setFontName("宋體");
- font2.setFontHeightInPoints((short) 10);// 設(shè)置字體大小
- fontStyle2.setFont(font2);
- fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下邊框
- fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左邊框
- fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上邊框
- fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右邊框
- fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
- }
-
- /**
- * 根據(jù)ExcelMapping 生成列頭(多行列頭)
- *
- * @param sheet
- * 工作簿
- * @param map
- * 每行每個單元格對應(yīng)的列頭信息
- */
- public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
- int startIndex=0;//cell起始位置
- int endIndex=0;//cell終止位置
-
- for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
- XSSFRow row = sheet.createRow(entry.getKey());
- List<ExcelBean> excels = entry.getValue();
- for (int x = 0; x < excels.size(); x++) {
- //合并單元格
- if(excels.get(x).getCols()>1){
- if(x==0){
- endIndex+=excels.get(x).getCols()-1;
- CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
- sheet.addMergedRegion(range);
- startIndex+=excels.get(x).getCols();
- }else{
- endIndex+=excels.get(x).getCols();
- CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
- sheet.addMergedRegion(range);
- startIndex+=excels.get(x).getCols();
- }
- XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
- cell.setCellValue(excels.get(x).getHeadTextName());// 設(shè)置內(nèi)容
- if (excels.get(x).getCellStyle() != null) {
- cell.setCellStyle(excels.get(x).getCellStyle());// 設(shè)置格式
- }
- cell.setCellStyle(fontStyle);
- }else{
-
- XSSFCell cell = row.createCell(x);
- cell.setCellValue(excels.get(x).getHeadTextName());// 設(shè)置內(nèi)容
- if (excels.get(x).getCellStyle() != null) {
- cell.setCellStyle(excels.get(x).getCellStyle());// 設(shè)置格式
- }
- cell.setCellStyle(fontStyle);
- }
-
- }
- }
- }
-
- /**
- *
- * @param sheet
- * @param map
- * @param objs
- * @param clazz
- */
- @SuppressWarnings("rawtypes")
- public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz)
- throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
- ClassNotFoundException, ParseException {
-
- int rowindex = map.size();
- int maxKey = 0;
- List<ExcelBean> ems = new ArrayList<>();
- for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
- if (entry.getKey() > maxKey) {
- maxKey = entry.getKey();
- }
- }
- ems = map.get(maxKey);
-
- List<Integer> widths = new ArrayList<Integer>(ems.size());
- for (Object obj : objs) {
- XSSFRow row = sheet.createRow(rowindex);
- for (int i = 0; i < ems.size(); i++) {
- ExcelBean em = (ExcelBean) ems.get(i);
- // 獲得get方法
- PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
- Method getMethod = pd.getReadMethod();
- Object rtn = getMethod.invoke(obj);
- String value = "";
- // 如果是日期類型 進(jìn)行 轉(zhuǎn)換
- if (rtn != null) {
- if (rtn instanceof Date) {
- value = DateUtils.date2String((Date) rtn,"yyyy-MM-dd");
- } else if(rtn instanceof BigDecimal){
- NumberFormat nf = new DecimalFormat("#,##0.00");
- value=nf.format((BigDecimal)rtn).toString();
- } else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){
- value="--";
- }else {
- value = rtn.toString();
- }
- }
- XSSFCell cell = row.createCell(i);
- cell.setCellValue(value);
- cell.setCellType(XSSFCell.CELL_TYPE_STRING);
- cell.setCellStyle(fontStyle2);
- // 獲得最大列寬
- int width = value.getBytes().length * 300;
- // 還未設(shè)置,,設(shè)置當(dāng)前
- if (widths.size() <= i) {
- widths.add(width);
- continue;
- }
- // 比原來大,,更新數(shù)據(jù)
- if (width > widths.get(i)) {
- widths.set(i, width);
- }
- }
- rowindex++;
- }
- // 設(shè)置列寬
- for (int index = 0; index < widths.size(); index++) {
- Integer width = widths.get(index);
- width = width < 2500 ? 2500 : width + 300;
- width = width > 10000 ? 10000 + 300 : width + 300;
- sheet.setColumnWidth(index, width);
- }
- }
- }
4. 在HTML頁面導(dǎo)入需要的js
- <script type="text/javascript" src="${ctxPath}/js/jquery-form.js"></script>
5. 在HTML添加測試控件
- <form id="uploadForm" enctype="multipart/form-data" method="post">
- <input id="upfile" type="file" name="upfile">
- <input type="button" value="導(dǎo)入" id="upLoadPayerCreditInfoExcel" name="btn">
- </form>
- <a href="${ctxPath}/creditInfo/downLoadReceverCreditInfoExcel.html">導(dǎo)出</a>
6. 導(dǎo)出通過a標(biāo)簽的get請求即可以實現(xiàn),導(dǎo)入則通過ajax的post請求實現(xiàn):
- $('#upLoadPayerCreditInfoExcel').click(function(){
- var cacheVersion=$("#cacheVersion").val();
- if(checkData()){
- $('#uploadForm').ajaxSubmit({
- url:$("#root").val()+'/creditInfo/uploadReceiverCreditInfoExcel.html',
- data:{'cacheVersion':cacheVersion},
- dataType: 'text'
- });
- }
- });
-
- //JS校驗form表單信息
- function checkData(){
- var fileDir = $("#upfile").val();
- var suffix = fileDir.substr(fileDir.lastIndexOf("."));
- if("" == fileDir){
- alert("選擇需要導(dǎo)入的Excel文件,!");
- return false;
- }
- if(".xls" != suffix && ".xlsx" != suffix ){
- alert("選擇Excel格式的文件導(dǎo)入,!");
- return false;
- }
- return true;
- }
7. controller端實現(xiàn)
導(dǎo)出:
- @RequestMapping(value = "/downLoadPayerCreditInfoExcel", method = RequestMethod.GET)
- @ResponseBody
- public void downLoadPayerCreditInfoExcel(HttpServletRequest request,HttpServletResponse response,HttpSession session){
- response.reset();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
- String dateStr = sdf.format(new Date());
- Long companyId=UserUtils.getCompanyIdBySession(session);
- Map<String,Object> map=new HashMap<String,Object>();
- // 指定下載的文件名
- response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xlsx");
- response.setContentType("application/vnd.ms-excel;charset=UTF-8");
- response.setHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
-
- XSSFWorkbook workbook=null;
- try {
- //導(dǎo)出Excel對象
- workbook = creditInfoService.exportPayerCreditInfoExcel(companyId);
- } catch (IllegalArgumentException | IllegalAccessException
- | InvocationTargetException | ClassNotFoundException
- | IntrospectionException | ParseException e1) {
- e1.printStackTrace();
- }
- OutputStream output;
- try {
- output = response.getOutputStream();
-
- BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
- bufferedOutPut.flush();
- workbook.write(bufferedOutPut);
- bufferedOutPut.close();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
導(dǎo)入:
- @ResponseBody
- @RequestMapping(value="uploadPayerCreditInfoExcel",method={RequestMethod.GET,RequestMethod.POST})
- Public void uploadPayerCreditInfoExcel(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- MultipartFile file = multipartRequest.getFile("upfile");
- if(file.isEmpty()){
- throw new Exception("文件不存在!");
- }
- Long companyId=UserUtils.getCompanyIdBySession(session);
- Long userId=UserUtils.getUserIdBySession(session);
- InputStream in = file.getInputStream();
- creditInfoService.uploadPayerCreditInfoExcel(in,file,companyId,userId);
- in.close();
- PrintWriter out = null;
- response.setCharacterEncoding("utf-8"); //防止ajax接受到的中文信息亂碼
- out = response.getWriter();
- out.print("文件導(dǎo)入成功,!");
- out.flush();
- out.close();
- }
8,、service層
導(dǎo)入,從excel中獲得數(shù)據(jù)放入List<List<object>>中,,然后遍歷放入實體,執(zhí)行插入操作:
- public void uploadPayerCreditInfoExcel(InputStream in, MultipartFile file,Long companyId,Long userId) throws Exception {
- List<List<Object>> listob = ExcelUtils.getBankListByExcel(in,file.getOriginalFilename());
- List<CreditInfoBean> creditInfoList=new ArrayList<CreditInfoBean>();
- for (int i = 0; i < listob.size(); i++) {
- List<Object> ob = listob.get(i);
- CreditInfoBean creditInfoBean = new CreditInfoBean();
- creditInfoBean.setCompanyName(String.valueOf(ob.get(0)));
- creditInfoBean.setBillType(String.valueOf(ob.get(1)));
- creditInfoBean.setBillNumber(String.valueOf(ob.get(2)));
- BigDecimal bd=new BigDecimal(String.valueOf(ob.get(3)));
- creditInfoBean.setBuyerBillAmount(bd.setScale(2, BigDecimal.ROUND_HALF_UP));
- creditInfoBean.setReceiveTime(String.valueOf(ob.get(4)));
- creditInfoBean.setBuyerRemark(String.valueOf(ob.get(5)));
- creditInfoList.add(creditInfoBean);
- }
- }
導(dǎo)出:
- public XSSFWorkbook exportPayerCreditInfoExcel(Long companyId) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, IntrospectionException, com.sun.tools.example.debug.expr.ParseException {
- List<CreditInfoBean> creditInfoList=creditInfoDao.listAllPayerCreditInfoPage(companyId);
- List<ExcelBean> ems=new ArrayList<>();
- Map<Integer,List<ExcelBean>>map=new LinkedHashMap<>();
- XSSFWorkbook book=null;
- ems.add(new ExcelBean("供應(yīng)商名稱","companyName",0));
- ems.add(new ExcelBean("票據(jù)類型","billType",0));
- ems.add(new ExcelBean("票據(jù)號","billNumber",0));
- // ems.add(new ExcelBean("買方是否參與","isBuyerIquidation",0));
- ems.add(new ExcelBean("票據(jù)金額","buyerBillAmount",0));
- ems.add(new ExcelBean("應(yīng)付日期","buyerPayTime",0));
- ems.add(new ExcelBean("剩余天數(shù)","overplusDays",0));
- ems.add(new ExcelBean("狀態(tài)","buyerBillStatus",0));
- map.put(0, ems);
- List<CreditInfoBean> afterChangeList=changeBuyerStatus(creditInfoList);
- book=ExcelUtils.createExcelFile(CreditInfoBean.class, afterChangeList, map, "應(yīng)付賬款信息");
- return book;
- }
|