Excel的導出

1.背景

       商家在抽獎C端發佈抽獎活動後,當該活動開獎,商家需要獲取中獎者的信息,兌現獎品。所以就需要將中獎者信息導出,形成一個excel文件,方便商家查看

 

2.poi介紹

簡介

           Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。

 

 

名稱解釋

名稱

含義

HSSFWorkbook

excel文檔對象

HSSFSheet

excel的sheet  

HSSFRow

excel的行

HSSFCell

excel的單元格 

HSSFFont

excel字體

HSSFName

名稱

HSSFDataFormat

日期格式

HSSFHeader

sheet頭

HSSFFooter 

sheet尾

HSSFCellStyle

cell樣式

 

導入Excel常用的方法

POIFSFileSystem   fs = new POIFSFileSystem(newFileInputStream("d:/test.xls"));  讀取excel文件

HSSFWorkbook  wb=new  HSSFWorkbook(fs); //得到Excel工作簿對象

HSSFSheet  sheet=wb.getSheetAt(0);//得到Excel工作表對象

HSSFRow   row=sheet.getRow(i);//得到Excel工作表的行

HSSFCell   cell=row.getCell((short)j); //得到Excel工作表指定行的單元格

cellStyle=cell.getCellStyle();//得到單元格樣式

 

 

導出Excel常用的方法

HSSFWorkbook  wb=new  HSSFWorkbook(); //創建Excel工作簿對象

HSSFSheet  sheet=wb.createSheet("newsheet"); //創建Excel工作表對象

HSSFRow  row=sheet.createRow((short)0); //創建Excel工作表的行

cellStyle=wb.createCellStyle(); //創建單元格樣式

row.createCell((short)0).setCellStyle(cellStyle); //創建Excel工作表指定行的單元格 row.createCell((short)0).setCellValue(1); //設置Excel工作表的值

 

3.springboot整合poi

添加依賴

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>

 

 

創建一個ExcelUtil類

 

導出

public static String exportToExcel(
            String sheetName, String sheetTableTitle, List<Object[]> dataList, Object[] filedName) {
        //創建一個輸出流
        OutputStream outputStream = null;
        //給生成的excel文件隨機生成一個名字,可自定義
        String fileName = FileUtils.getName("xlsx");
        try {
            //創建一個名爲fileName的file對象,方便後續寫操作
            File file = new File(fileName);
            //實例化輸出流對象
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        exportToExcel(outputStream, sheetName, sheetTableTitle, dataList, filedName);

        return fileName;
    }
private static void exportToExcel(OutputStream outputStream,
                                      String sheetName, String sheetTableTitle, List<Object[]> dataList, Object[] filedName) {
        // 創建工作簿對象
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            // 創建工作表
            XSSFSheet sheet = workbook.createSheet(sheetName);                                   
            // 產生表格標題行 
            XSSFRow rowM = sheet.createRow(0);
            XSSFCell cellTitle = rowM.createCell(0);

            //sheet樣式定義
            // 獲取列頭樣式對象
            XSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);
            // 單元格樣式對象
            XSSFCellStyle style = getStyle(workbook);
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, filedName.length));
            cellTitle.setCellStyle(columnTopStyle);
            cellTitle.setCellValue(sheetTableTitle);

            // 定義所需列數
            int columnNum = filedName.length + 1;
            // 在索引2的位置創建行(最頂端的行開始的第二行)
            XSSFRow rowRowName = sheet.createRow(2);

            // 將列頭設置到sheet的單元格中
            for (int n = 0; n < columnNum; n++) {
                //創建列頭對應個數的單元格
                XSSFCell cellRowName = rowRowName.createCell(n);
                //設置列頭單元格的數據類型
                cellRowName.setCellType(XSSFCell.CELL_TYPE_STRING);
                XSSFRichTextString text;
                if (n == 0) {
                    text = new XSSFRichTextString("序號");
                } else {
                    text = new XSSFRichTextString(filedName[n - 1].toString());
                }
                //設置列頭單元格的值
                cellRowName.setCellValue(text);
                //設置列頭單元格樣式
                cellRowName.setCellStyle(columnTopStyle);
            }

            //插入數據
            if (dataList != null && !dataList.isEmpty()) {
                for (int i = 0; i < dataList.size(); i++) {
                    //遍歷每個對象
                    Object[] obj = dataList.get(i);
                    //創建所需的行數
                    XSSFRow row = sheet.createRow(i + 3);

                    for (int j = 0; j < obj.length + 1; j++) {
                        //設置單元格的數據類型
                        XSSFCell cell = null;
                        if (j == 0) {
                            cell = row.createCell(j, XSSFCell.CELL_TYPE_NUMERIC);
                            cell.setCellValue(i + 1);
                        } else {
                            cell = row.createCell(j, XSSFCell.CELL_TYPE_STRING);
                            if (obj[j - 1] == null) {
                                cell.setCellValue("");
                            } else {
                                cell.setCellValue(obj[j - 1].toString());
                            }
                        }
                        cell.setCellStyle(style);
                    }
                }
            } else {
                XSSFRow rowNoData = sheet.createRow(3);
                XSSFCell noDataCellTitle = rowNoData.createCell(0);
                sheet.addMergedRegion(new CellRangeAddress(3, 5, 0, filedName.length));
                noDataCellTitle.setCellStyle(columnTopStyle);
                noDataCellTitle.setCellValue("無數據");
            }

            //讓列寬隨着導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    XSSFRow currentRow;
                    //當前行未被使用過
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        XSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            }
            //將數據寫入到新建的Excel表格中
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            //文件不存在
            logger.error("File not found or had opened, error = {}", e.getLocalizedMessage());
        } catch (Exception e) {
            //導出成excel文件失敗
            logger.error("Export data failure, error = {}", e.getLocalizedMessage());
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                logger.error("workbook close failure, error = {}", e.getLocalizedMessage());
            }
        }
    }               

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章