java生成Excel

来源:互联网 发布:ubuntu 查看硬盘大小 编辑:程序博客网 时间:2024/05/16 01:47
public static void write(OutputStream outputStream, List<?> lists, List<Grid> grids) throws IOException {
// 初始一个workbook
HSSFWorkbook workbook = new HSSFWorkbook();


// 每个sheet表存60000条数据
int sheetNum = lists.size() / 60000;


// 循环创建多个sheet
for (int sheetIndex = 0; sheetIndex < sheetNum + 1; sheetIndex++) {
HSSFSheet sheet = workbook.createSheet("sheet" + sheetIndex);


// 创建表头
HSSFRow rowTitle = sheet.createRow(0);
int rowNum = 0;
for (Grid grid : grids) {
HSSFCell cell = rowTitle.createCell(rowNum);
cell.setCellValue(grid.getText());
rowNum++;
}


//数据量
int dataNum = 0;
if(sheetIndex == sheetNum){
dataNum = lists.size()-sheetIndex*60000;
}else{
dataNum = 60000;
}

// 创建多行
for (int rowIndex = 0; rowIndex < dataNum; rowIndex++) {
HSSFRow row = sheet.createRow(rowIndex + 1);


Object list = lists.get(rowIndex + sheetIndex*60000);
// 创建多列
int cellnum = 0;
for (Grid grid : grids) {
HSSFCell cell = row.createCell(cellnum);
Object value = getFieldValueByName(grid.getId(), list);
if (value == null) {
cell.setCellValue("");
} else {
cell.setCellValue(value.toString());
}


cellnum++;
}
}
}


workbook.write(outputStream);

}


public static void ExcelExport(List<?> lists, List<Grid> grids, HttpServletResponse response, HttpServletRequest request) {
OutputStream outputStream = null;
try {
String rootPath = request.getSession().getServletContext().getRealPath("/");
String path = rootPath + "Download";
File filePath =new File(path);    
//如果文件夹不存在则创建    
if  (!filePath .exists()  && !filePath .isDirectory())      
{       
   filePath .mkdir();    


String fileName = filePath + "\\" + (new Date()).getTime() + ".xls";
File file = new File(fileName);
outputStream = new FileOutputStream(file);
//生成Excel
write(outputStream, lists, grids);


//弹出下载框
download(fileName, response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

0 0
原创粉丝点击