java導出excel

數據導出到Excel幾乎是所有客戶都會提出的一個需求。下面我就分享一下我的代碼。

首先需要引入的jar包:

然後就是正式代碼了。


package lcy._41_50;
 
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 static void main(String[] args) throws Exception {
 
        String sheetName = "用車統計表單";
        String titleName = "用車申請數據統計表";
        String fileName = "用車申請統計表單";
        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 = { "單號", "申請時間", "申請部門" };
        new Test46().ExportNoResponse(sheetName, titleName, fileName,
                columnNumber, columnWidth, columnName, dataList);
    }
 
    public void ExportWithResponse(String sheetName, String titleName,
            String fileName, int columnNumber, int[] columnWidth,
            String[] columnName, String[][] dataList,
            HttpServletResponse response) throws Exception {
        if (columnNumber == columnWidth.length&& columnWidth.length == columnName.length) {
            // 第一步,創建一個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)); // 合併列標題
            cell1.setCellValue(titleName); // 設置值標題
            cell1.setCellStyle(style2); // 設置標題樣式
 
            // 創建第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);
                HSSFCell datacell = null;
                for (int j = 0; j < columnNumber; j++) 
                {
                    datacell = row.createCell(j);
                    datacell.setCellValue(dataList[i][j]);
                    datacell.setCellStyle(zidonghuanhang2);
                }
            }
 
            // 第六步,將文件存到瀏覽器設置的下載位置
            String filename = fileName + ".xls";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
            OutputStream out = response.getOutputStream();
            try {
                wb.write(out);// 將數據寫出去
                String str = "導出" + fileName + "成功!";
                System.out.println(str);
            } catch (Exception e) {
                e.printStackTrace();
                String str1 = "導出" + fileName + "失敗!";
                System.out.println(str1);
            } finally {
                out.close();
            }
 
        } else {
            System.out.println("列數目長度名稱三個數組長度要一致");
        }
 
    }
 
    public void ExportNoResponse(String sheetName, String titleName,
            String fileName, int columnNumber, int[] columnWidth,
            String[] columnName, String[][] dataList) throws Exception {
        if (columnNumber == columnWidth.length&& columnWidth.length == columnName.length) {
            // 第一步,創建一個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); // 設置標題樣式
 
            // 創建第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);
                HSSFCell datacell = null;
                for (int j = 0; j < columnNumber; j++) 
                {
                    datacell = row.createCell(j);
                    datacell.setCellValue(dataList[i][j]);
                    datacell.setCellStyle(zidonghuanhang2);
                }
            }
 
            // 第六步,將文件存到指定位置
            try {
                FileOutputStream fout = new FileOutputStream("D:students.xls");
                wb.write(fout);
                String str = "導出" + fileName + "成功!";
                System.out.println(str);
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
                String str1 = "導出" + fileName + "失敗!";
                System.out.println(str1);
            }
        } else {
            System.out.println("列數目長度名稱三個數組長度要一致");
        }
 
    }
 
}
爲了本地測試效果,單獨寫了一個無response參數的ExportNoResponse方法,直接將文件保存到指定目錄D盤。
兩個方法的不同就在於第六步中,有response參數的方法可以將文件存到瀏覽器設置的下載位置。
下面是導出效果截圖:

 將excel導出需要用response流

protected void write(HSSFWorkbook workbook, HttpServletResponse response) throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=" + getTimeString("xls"));
    OutputStream ouputStream = response.getOutputStream();
    workbook.write(ouputStream);
    ouputStream.flush();
    ouputStream.close();
}
/**
 * 描述 根據時間生成文件名
 * @created 2015-11-11 下午3:56:05
 * @param fileName
 * @return
 */
private String getTimeString(String fileName) {
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 設置日期格式
    Date date = new Date();// new Date()爲獲取當前系統時間
    return df.format(date) + "." + fileName;
}

前端代碼

window.open(window.location.protocol + "dispatch/jobMonitor/exportRequestExcel" + '?type='
  + this.type1 + '&name=' + encodeURI(this.name), 'loading'); 

或者

window.location.href="/report/exportBooksTable.do;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章