`

poi导出excel

阅读更多
代码比较简洁的一种导出excel方式,嘿嘿,保存下来。
package util.report;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
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.HSSFRichTextString;
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.HSSFColor;

public class CommonReportExcelBuilder {

    private static final int startRow = 0;

    private static final int startColumn = 0;

    public static final String[] columnHeader = {"tid", "日志编号", "发表用户", "用户ID", "日志标题", "发表时间", "审核人", "审核时间", "分配时间"};

     
    /**
     * @param table
     * @return
     * @throws Exception
     */
	public String create(Table table) throws Exception {
        String filepath = System.getProperty("java.io.tmpdir");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String fileName = filepath + File.separator + format.format(new Date()) + ".xls";
        File f = new File(fileName);// 文件设置
        FileOutputStream fos = new FileOutputStream(f);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = null;
        try {
            sheet = wb.createSheet();
            sheet.setDefaultColumnWidth(18);
            fullSheet(wb, sheet, table);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.flush();
            fos.close();
        }
        return fileName;
    }

    /**
     * 将文件写到客户端
     *
     * @param response
     * @param filename    文件的绝对路径
     * @param filedisplay 导出到客户端的文件名称
     * @throws Exception
     */
    public void export(HttpServletResponse response, String filename,
                       String filedisplay) throws Exception {

        OutputStream out = null;
        FileInputStream in = null;
        try {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            in = new FileInputStream(filename);
            filedisplay = URLEncoder.encode(filedisplay, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + filedisplay + ".xls");
            byte[] b = new byte[512];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                out.write(b, 0, i);
            }
            out.flush();
        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
    
    /**
     * 填充sheet
     *
     * @param sheet
     * @param table
     */
    private void fullSheet(HSSFWorkbook wb, HSSFSheet sheet, Table table) {
        HSSFRow head = sheet.createRow(startRow);
        head.setHeightInPoints(20);
        String[] columnHeader = table.getColumnHeader();
        for (int i = 0; i < columnHeader.length; i++) {
            HSSFCell cell = head.createCell(startColumn + i);
            cell.setCellStyle(getHeadCellStyle(wb));
            cell.setCellValue(columnHeader[i]);
        }
        List<String[]> dataList = table.getDataList();
        for (int i = 0; i < dataList.size(); i++) {
            HSSFRow tr = sheet.createRow((startRow + 1) + i);
            String[] tds = dataList.get(i);
            for (int j = 0; j < tds.length; j++) {
                HSSFCell cell = tr.createCell(startColumn + j);
                cell.setCellStyle(getDataCellStyle(wb));
                cell.setCellValue(new HSSFRichTextString(tds[j]));
            }
        }
    }

    /**
     * 获取cell style
     *
     * @param wb
     * @return
     */
    private HSSFCellStyle getDataCellStyle(HSSFWorkbook wb) {
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 10); // 字体高度
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 宽度
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 边框
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);
        cellStyle.setFont(font);

        return cellStyle;
    }

    private HSSFCellStyle getHeadCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle headStyle = wb.createCellStyle();
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 边框
        headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

        HSSFFont font = wb.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 10);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headStyle.setFont(font);
        return headStyle;
    }
}


构建table对象
package util.report;

import java.util.List;

public class Table {

    private String title;

    private String[] columnHeader;

    private List<String[]> dataList;

    public Table() {

    }

    public Table(String title, String[] columnHeader, List<String[]> dataList) {
        this.title = title;
        this.columnHeader = columnHeader;
        this.dataList = dataList;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String[] getColumnHeader() {
        return columnHeader;
    }

    public void setColumnHeader(String[] columnHeader) {
        this.columnHeader = columnHeader;
    }

    public List<String[]> getDataList() {
        return dataList;
    }

    public void setDataList(List<String[]> dataList) {
        this.dataList = dataList;
    }
}
 在需要导出的地方开始导出
Table table = new Table(null, 表头.toArray(new String[] {}), 数据集合是这个类型(List<String[]>));
		CommonReportExcelBuilder reportExcelBuilder = new CommonReportExcelBuilder();
		try {
			String fileName = reportExcelBuilder.create(table);
			if (logger.isDebugEnabled()) {
				logger.debug("导出文件全路径:" + fileName);
			}
			reportExcelBuilder.export(context.getResponse(), fileName, "信息审核报表");

		} catch (Exception e) {
			logger.error("导出信息审核报表出现异常", e);
		}
当然忘记还有就是把 poi所需要的bao添加到项目里面,我的是已经在自己的资源库里了,所以在poi里面配置一下poi版本是3.6
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
    </dependency>
OK,完成,成功导出,

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics