我正在使用Apache POI并扩展Springs AbstractExcelView来创建Excel工作表。
public class ExcelSpreadsheetView extends AbstractExcelView {
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//GET POSITIONS TO LOOP THROUGH FROM MODEL
@SuppressWarnings("unchecked")
List<Position> positions = (List<Position>) model.get("positions");
int lastRow = 0;
mySheet = wb.createSheet("SHEET1");
myRow = mySheet.createRow(lastRow);
myCell = myRow.createCell(0);
//loop through positions
for (int p = 0; p < positions.size(); p++) {
myRow = mySheet.createRow(lastRow);
myCell = myRow.createCell(0);
myCell.setCellValue(new HSSFRichTextString(positions.get(p).getPositionName()));
lastRow++;
}
//response stuff goes here, but I shouldnt need it
}
当我在所有POI代码后面有以下代码时,我可以成功创建工作表:
response.setHeader("Content-Disposition", "inline;filename=\"spreadsheet.xls\"");
response.setContentType("APPLICATION/OCTET-STREAM");
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
事实上,在网上没有一个例子中,人们包括写出OutputStream或设置ContentType,看起来像AbstractExcelView处理它。
当我注释掉上面的6行时,它会尝试创建文件(我可以在控制台日志中看到它正确解析所有数据),但是当我打开文件时,Excel无法打开它并显示以下内容:
“文件错误:数据可能已丢失。”
我知道我的代码按原样运行,我只是尝试以正确的方式执行并遵循其他人在线进行的操作。我不认为我在OutputStream或ContentType中有代码,但只有在我这样做时才有效。
非常感谢任何帮助!
答案 0 :(得分:1)
请给我更多代码。
您使用HSSFSheet吗?
public class ExcelReportView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// create a wordsheet
HSSFSheet sheet = workbook.createSheet("Title");
HSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("whatever");
header.createCell(1).setCellValue("whatever");
int rowNum = 1;
for (...) {
// create the row data
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue("whatever");
row.createCell(1).setCellValue("whatever");
}
}
}