1. 程式人生 > >Java(poi)導出Excel數據

Java(poi)導出Excel數據

Java;poi;導出Excel數據

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;

@SuppressWarnings( { "deprecation" })
public class Test46 {

public void Excel(HttpServletRequest request, HttpServletResponse response) throws Exception {

String sheetName = "用車統計表單";
    String titleName = "用車申請數據統計表";
    String title2Name = "自查日期:";
    String fileName = "用車申請統計表單";
    String beiZhuName ="備註:1.測試 。\r\n2.測試 。\r\n3.測試 。";//**設置強制換行“\r\n”**
    int columnNumber = 3;
    int[] columnWidth = { 10, 20, 30 };
    String[][] dataList = { { "001", "2015-01-01", "IT" },
            { "002", "2015-01-02", "市場部" }, { "003", "2015-01-03", "測試" } };
    String[] columnName = { "單號", "申請時間", "申請部門" };
}
        // 第一步,創建一個webbook,對應一個Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // sheet.setDefaultColumnWidth(15); //統一設置列寬
        for (int i = 0; i < columnNumber; i++) 
        {
            for (int j = 0; j <= i; j++) 
            {
                if (i == j) 
                {
                    sheet.setColumnWidth(i, columnWidth[j] * 256); // 單獨設置每列的寬
                }
            }
        }
        // 創建第0行 也就是標題
        HSSFRow row1 = sheet.createRow((int) 0);
        row1.setHeightInPoints(50);// 設備標題的高度
        // 第三步創建標題的單元格樣式style2以及字體樣式headerFont1
        HSSFCellStyle style2 = wb.createCellStyle();
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 創建字體樣式
        headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體加粗
        headerFont1.setFontName("黑體"); // 設置字體類型
        headerFont1.setFontHeightInPoints((short) 15); // 設置字體大小
        style2.setFont(headerFont1); // 為標題樣式設置字體樣式

        HSSFCell cell1 = row1.createCell(0);// 創建標題第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
                columnNumber - 1)); // 合並第0到第17列
        cell1.setCellValue(titleName); // 設置值標題
        cell1.setCellStyle(style2); // 設置標題樣式

        // 創建 時間
        HSSFRow row2 = sheet.createRow((int) 1);
        row2.setHeightInPoints(21);// 設置時間高度
        // 創建時間 單元格樣式 以及表頭的字體樣式
        HSSFCellStyle style2 = wb.createCellStyle();
        style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 創建一個靠右格式 水平方向
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直方向
        HSSFFont headerFont2 = (HSSFFont) wb.createFont(); // 創建字體樣式
        headerFont2.setFontName("楷體"); // 設置字體類型
        headerFont2.setFontHeightInPoints((short) 12); // 設置字體大小
        style2.setFont(headerFont2); // 為標題樣式設置字體樣式
        HSSFCell cell2 = row2.createCell(0);// 設置值在第一列
         // 合並列標題 在用poi在EXECL報表設計的時候,遇到單元格合並問題,
         //用到一個重要的函數:CellRangeAddress(int, int, int, int)
         //參數:起始行號,終止行號, 起始列號,終止列號
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, columnNumber - 1));
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy年MM月dd日");
        String date2 = df2.format(new Date());
        cell2.setCellValue(title2Name + date2); // 設置值標題
        cell2.setCellStyle(style2); // 設置標題樣式

        // 創建備註
        HSSFRow row3 = sheet.createRow((int) 12);
        row3.setHeightInPoints(71);// 設備標題的高度
        // 第三步創建標題的單元格樣式style2以及字體樣式headerFont1
        HSSFCellStyle style3 = wb.createCellStyle();
        style3.setWrapText(true);// 設置自動換行
        style3.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 水平靠左
        style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直方向
        HSSFFont headerFont3 = (HSSFFont) wb.createFont(); // 創建字體樣式
        headerFont3.setFontName("仿宋"); // 設置字體類型
        headerFont3.setFontHeightInPoints((short) 11); // 設置字體大小
        style3.setFont(headerFont3); // 為標題樣式設置字體樣式

        HSSFCell cell3 = row3.createCell(0);// 創建標題第一列
        sheet.addMergedRegion(new CellRangeAddress(12, 12, 0, columnNumber - 1)); // 合並列標題
        cell3.setCellValue(beiZhuName); // 設置值標題
        cell3.setCellStyle(style3); // 設置標題樣式

        // 創建第1行 也就是表頭
        HSSFRow row = sheet.createRow((int) 2);
        row.setHeightInPoints(25);// 設置表頭高度

        // 創建第1行 也就是表頭
        HSSFRow row = sheet.createRow((int) 1);
        row.setHeightInPoints(37);// 設置表頭高度

        // 第四步,創建表頭單元格樣式 以及表頭的字體樣式
        HSSFCellStyle style = wb.createCellStyle();
        style.setWrapText(true);// 設置自動換行
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 創建一個居中格式

        style.setBottomBorderColor(HSSFColor.BLACK.index);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);

        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 創建字體樣式
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體加粗
        headerFont.setFontName("黑體"); // 設置字體類型
        headerFont.setFontHeightInPoints((short) 10); // 設置字體大小
        style.setFont(headerFont); // 為標題樣式設置字體樣式

        // 第四.一步,創建表頭的列
        for (int i = 0; i < columnNumber; i++) 
        {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(columnName[i]);
            cell.setCellStyle(style);
        }

        // 第五步,創建單元格,並設置值
        for (int i = 0; i < dataList.length; i++) 
        {
            row = sheet.createRow((int) i + 2);
            // 為數據內容設置特點新單元格樣式1 自動換行 上下居中
            HSSFCellStyle zidonghuanhang = wb.createCellStyle();
            zidonghuanhang.setWrapText(true);// 設置自動換行
            zidonghuanhang
                    .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 創建一個居中格式

            // 設置邊框
            zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
            zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);

            // 為數據內容設置特點新單元格樣式2 自動換行 上下居中左右也居中
            HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
            zidonghuanhang2.setWrapText(true);// 設置自動換行
            zidonghuanhang2
                    .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 創建一個上下居中格式
            zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

            // 設置邊框
            zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
            zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
            zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
            HSSFFont neiRongFont = (HSSFFont) wb.createFont(); // 創建內容字體樣式
            neiRongFont.setFontName("宋體"); // 設置內容字體類型
            neiRongFont.setFontHeightInPoints((short) 11); // 設置內容字體大小
            zidonghuanhang2.setFont(neiRongFont); // 為內容樣式設置字體樣式
            HSSFCell datacell = null;
            for (int j = 0; j < columnNumber; j++) 
            {
                datacell = row.createCell(j);
                datacell.setCellValue(dataList[i][j]);
                datacell.setCellStyle(zidonghuanhang2);
            }
        }

    // 輸出Excel文件  ,直接找到瀏覽器設置的下載地址,下載完成
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String date = sdf.format(new Date());
            OutputStream output = response.getOutputStream();
            String filename = fileName + date + ".xls";
            response.getOutputStream().write(1);
            response.reset();
            response.setHeader("Content-disposition",
                    "attachment; filename=".concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
            response.setContentType("application/msexcel;charset=UTF-8");//設置導出的文件名稱為UTF-8格式,支持漢字名稱+時間
            wb.write(output);
            wb.close();
            output.flush();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

}
推薦一個poi知識點很全的博客地址:https://www.cnblogs.com/azhqiang/p/4362090.html

Java(poi)導出Excel數據