使用poi導出數據到excel


一、首先是導入poi所需要的jar包,我是用的是maven,添加jar包依賴

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

二、導出excel工具類代碼編寫

package com.cccuu.project.myUtils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/******************************************* 
 *
 * @Package com.cccuu.project.myUtils
 * @Author duan
 * @Date 2018/3/29 9:12
 * @Version V1.0
 *******************************************/
public class ExcelUtil {


    /**
     * 導出excel
     * @param title  導出表的標題
     * @param rowsName 導出表的列名
     * @param dataList  需要導出的數據
     * @param fileName  生成excel文件的文件名
     * @param response
     */
    public void exportExcel(String title,String[] rowsName,List<Object[]> dataList,String fileName,HttpServletResponse response) throws Exception{
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition",
                "attachment; filename="+fileName);
        response.setContentType("application/msexcel");
        this.export(title,rowsName,dataList,fileName,output);
        this.close(output);

    }



    /*
     * 導出數據
     */
    private void export(String title,String[] rowName,List<Object[]> dataList,String fileName,OutputStream out) throws Exception {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(); // 創建工作簿對象
            HSSFSheet sheet = workbook.createSheet(title); // 創建工作表
            HSSFRow rowm = sheet.createRow(0);  // 產生表格標題行
            HSSFCell cellTiltle = rowm.createCell(0);   //創建表格標題列
            // sheet樣式定義;    getColumnTopStyle();    getStyle()均為自定義方法 --在下面,可擴展
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 獲取列頭樣式對象
            HSSFCellStyle style = this.getStyle(workbook); // 獲取單元格樣式對象
            //合並表格標題行,合並列數為列名的長度,第一個0為起始行號,第二個1為終止行號,第三個0為起始列好,第四個參數為終止列號
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
            cellTiltle.setCellStyle(columnTopStyle);    //設置標題行樣式
            cellTiltle.setCellValue(title);     //設置標題行值
            int columnNum = rowName.length;     // 定義所需列數
            HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置創建行(最頂端的行開始的第二行)
            // 將列頭設置到sheet的單元格中
            for (int n = 0; n < columnNum; n++) {
                HSSFCell cellRowName = rowRowName.createCell(n); // 創建列頭對應個數的單元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 設置列頭單元格的數據類型
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text); // 設置列頭單元格的值
                cellRowName.setCellStyle(columnTopStyle); // 設置列頭單元格樣式
            }

            // 將查詢出的數據設置到sheet對應的單元格中
            for (int i = 0; i < dataList.size(); i++) {
                Object[] obj = dataList.get(i);   // 遍歷每個對象
                HSSFRow row = sheet.createRow(i + 3);   // 創建所需的行數
                for (int j = 0; j < obj.length; j++) {
                    HSSFCell cell = null;   // 設置單元格的數據類型
                    if (j == 0) {
                        cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(i + 1);
                    } else {
                        cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
                        if (!"".equals(obj[j]) && obj[j] != null) {
                            cell.setCellValue(obj[j].toString()); // 設置單元格的值
                        }
                    }
                    cell.setCellStyle(style); // 設置單元格樣式
                }
            }

            // 讓列寬隨着導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    // 當前行未被使用過
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellType() == HSSFCell.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);
                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 列頭單元格樣式
     */
    private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 設置字體
        HSSFFont font = workbook.createFont();
        // 設置字體大小
        font.setFontHeightInPoints((short) 11);
        // 字體加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 設置字體名字
        font.setFontName("Courier New");
        // 設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在樣式用應用設置的字體;
        style.setFont(font);
        // 設置自動換行;
        style.setWrapText(false);
        // 設置水平對齊的樣式為居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 設置垂直對齊的樣式為居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

    /*
     * 列數據信息單元格樣式
     */
    private HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 設置字體
        HSSFFont font = workbook.createFont();
        // 設置字體大小
        // font.setFontHeightInPoints((short)10);
        // 字體加粗
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 設置字體名字
        font.setFontName("Courier New");
        // 設置樣式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 設置底邊框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 設置底邊框顏色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 設置左邊框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 設置左邊框顏色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 設置右邊框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 設置右邊框顏色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 設置頂邊框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 設置頂邊框顏色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在樣式用應用設置的字體;
        style.setFont(font);
        // 設置自動換行;
        style.setWrapText(false);
        // 設置水平對齊的樣式為居中對齊;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 設置垂直對齊的樣式為居中對齊;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        return style;
    }

    /**
     * 關閉輸出流
     * @param os
     */
    private void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

三、測試,框架使用的是ssm

@RequestMapping("exportWordData")
    public void exportExcelData(HttpServletRequest request,HttpServletResponse response){
        // 定義表的標題
        String title = "員工列表一覽";
        //定義表的列名
        String[] rowsName = new String[] { "序號", "姓名", "性別", "特長", "學歷", "入職時間", "簡歷", "照片", "部門" };
        //定義表的內容
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = new Object[9];
        objs[0] = "測試";
        objs[1] = 11;
        objs[2] = "111";
        objs[3] = "測試";
        objs[4] = "測試";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(2018-12-24);
        objs[5] = date;
        objs[6] = "測試";
        objs[7] = "測試";
        objs[8] = "測試";
        dataList.add(objs);
        // 創建ExportExcel對象
        ExcelUtil excelUtil = new ExcelUtil();

        try{
            String fileName= new String("測試excel文檔.xlsx".getBytes("UTF-8"),"iso-8859-1");    //生成word文件的文件名
            excelUtil.exportExcel(title,rowsName,dataList,fileName,response);
            returnInfo.setResult(true);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM