POI 简单的一个小demo
程序员文章站
2022-07-07 14:03:28
...
/**
* 下载测试方法
* @param response
*/
public void downLoad(final HttpServletRequest request,final HttpServletResponse response){
Workbook wb = new HSSFWorkbook(); //创建文档类型
Sheet sheet = wb.createSheet("测试下载"); //创建工作表对象
CellStyle cellStyle = wb.createCellStyle(); //创建单元格样式
//设置背景色
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
cellStyle.setFillBackgroundColor(HSSFColor.RED.index);
cellStyle.setFillPattern(HSSFColor.RED.index);
String[] headStr = new String[]{"姓名","性别","收入"};
int rowIdx = 0;
int cellIdx = 0;
Row createRow = sheet.createRow(rowIdx++);
for(int i=0; i<headStr.length; i++){
Cell cell = createRow.createCell(cellIdx++);
cell.setCellValue(headStr[i]);
cell.setCellStyle(cellStyle);
// sheet.autoSizeColumn(i);
}
createRow = sheet.createRow(rowIdx++);
cellIdx = 0;
//设置字体
Font font = wb.createFont();
font.setColor(HSSFColor.YELLOW.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //字体加粗
cellStyle.setFont(font);
for(int i=0; i<3; i++){
Cell cell = createRow.createCell(cellIdx++);
cell.setCellValue(i);
cell.setCellStyle(cellStyle);
}
//
String fileNamestr = "下载测试单" + new java.util.Date().getTime();
OutputStream output = null;
try {
response.setHeader("Content-disposition","attachment; filename="
+ new String(fileNamestr.getBytes("gb2312"), "ISO8859-1" ));
response.setCharacterEncoding("UTF-8");
output = response.getOutputStream(); // 读取的文件路径
response.setContentType("application/vnd.ms-excel");
wb.write(output);
output.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null != output){
try {
output.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
效果展示: