java根据excel 模板导出excel
//这个用模板导出,省略了创建表头的方法,可以把模板里面的全部复制下来,放到要导出的excel里面
//首先要记住,excel 第一行是从0开始的,列也是如此
//访问方法
public String na(HttpServletResponse response,HttpServletRequest request){
//查询要到处的数据
List<Map<string,string>> dataSourceList= null;
try {
ExcelDownloadUtil.ExcelByModel("测试模板导出", modelURLString, dataSourceList, response, sheetNameStrings, keysStrings, 6);
} catch (Exception e) {
e.printStackTrace();
}
return "SUCESS";
}
在模板中添加数据
public static void ExcelByModel(String ExcelName, String ModelURl, List<Map<String,String>> dataSource,HttpServletResponse response, String[] sheetNames, String[] keyNames, int rowNum) throws Exception {
// 设置导出Excel报表的导出形式
response.setContentType("application/vnd.ms-excel");
// 设置导出Excel报表的响应文件名
String fileName = new String(ExcelName.getBytes("utf-8"), "ISO-8859-1");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");//导出的文件名称
// 创建一个输出流
OutputStream fileOut = response.getOutputStream();
// 读取模板文件路径
File file = new File(ModelURl);
FileInputStream fins = new FileInputStream(file);
POIFSFileSystem fs = new POIFSFileSystem(fins);
// 读取Excel模板
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);//获取第一页sheet页
sheet.autoSizeColumn(1);
HSSFRow rowCellStyle1 = sheet.getRow(2);//sheet页的第二行
HSSFCellStyle columnOne01 = rowCellStyle1.getCell(0).getCellStyle();//获取sheet页第二行的样式
// 设置边框样式(样式自己选择)
// HSSFCellStyle style = wb.createCellStyle();
// style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// style.setBorderTop (HSSFCellStyle.BORDER_THIN);
// 设置边框样式的颜色
// style.setBottomBorderColor(HSSFColor.BLACK.index);
// style.setLeftBorderColor(HSSFColor.BLACK.index);
// style.setRightBorderColor(HSSFColor.BLACK.index);
// style.setTopBorderColor(HSSFColor.BLACK.index);
for (int j = 0; j <20; j++) {
HSSFRow row = sheet.getRow(j+3);// 创建第二行
HSSFCell cellHeard1 = row.getCell(1); //获取模板的第2个单元格b
HSSFCell cellHeard2 = row.getCell(2);
HSSFCell cellHeard3 = row.getCell(3);
HSSFCell cellHeard4 = row.getCell(4);
HSSFCell cellHeard5 = row.getCell(5);
HSSFCell cellHeard6 = row.getCell(6);
HSSFCell cellHeard7 = row.getCell(7);
// 在该单元格内输入内容
cellHeard1.setCellValue(j+1); //序号
cellHeard1.setCellStyle(columnOne01);//获取模板单元格样式
//单元格添加数据
cellHeard2.setCellValue("1");
cellHeard2.setCellStyle(columnOne01);
//单元格添加数据
cellHeard3.setCellValue("2");
cellHeard3.setCellStyle(columnOne01);
//单元格添加数据
cellHeard4.setCellValue(3);
cellHeard4.setCellStyle(columnOne01);
//单元格添加数据
cellHeard5.setCellValue(4);
cellHeard5.setCellStyle(columnOne01);
//单元格添加数据
cellHeard6.setCellValue(5);
cellHeard6.setCellStyle(columnOne01);
//单元格添加数据
cellHeard7.setCellValue(6);
cellHeard7.setCellStyle(columnOne01);
}
// 写入流
wb.write(fileOut);
// 关闭流
fileOut.close();
}