java的excel导出的简单示例

java的excel导出的简单示例

直接上代码吧,很简单易懂的excel导出。

代码块

代码:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

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

public class export {

    public void testExport( HttpServletResponse response){
        List<String> exportList = new ArrayList<>();
        exportList.add("测");
        exportList.add("试");
        exportList.add("例");
        exportList.add("子");
        String titelName = "测试导出";
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet();
        workBook.setSheetName(0, titelName);
        HSSFCellStyle cellStyle = workBook.createCellStyle();// 创建一个单元的样式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellStyle.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);// 上下居中
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        String[] titles = { "序号", "", "例子"};
        for (int i = 0; i < titles.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(cellStyle);
            sheet.setColumnWidth(i, 5000);
        }
        int i = 1;
        for (String el : exportList){
            Object[] values = {i,el};
            row = sheet.createRow(i);
            for (int j = 0; j < values.length; j++) {
                cell = row.createCell(j);
                String value = String.valueOf(values[j]);
                if (value == null || value.equalsIgnoreCase("null")) {
                    value = "-";
                }
                cell.setCellValue(value);
                cell.setCellStyle(cellStyle);
            }
            i++;
        }
        // 通过Response把数据以Excel格式保存
        try {
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + new String((titelName + ".xls").getBytes("GB2312"), "ISO8859-1") + "\"");
            OutputStream out = response.getOutputStream();
            workBook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.print("生成测试列表excel失败:{}"+e);
        }
    }

}

你可能感兴趣的:(java)