小生のコードで、maihamaさんの部分を// TODO としたコードです。
参考になれば、使ってみてください。
xlsxへの操作はpoiを使ってます。
public boolean Excel_export() {
String[] file = new String[2];
try {
file = createReport();
if (!file[0].equals("error")) {
HttpServletRequest req = getContext().getRequest();
HttpServletResponse res = getContext().getResponse();
File fileOut = new File(file[0]);
@SuppressWarnings({ "resource", "unused" })
FileInputStream hFile = new FileInputStream(fileOut.getPath());
printOutFile(req, res, fileOut, file[1]);
}
} catch (Exception e) {
// TODO
// 使用しているテンプレートに併せて、エラーメッセージをViewへ表示させる。
log.error("異常:Excel_export() : " + e.toString());
}
return true;
}
protected void printOutFile(HttpServletRequest req, HttpServletResponse res, File fileOut, String filename)
throws ServletException, IOException {
filename = URLEncoder.encode(filename, "UTF-8");
OutputStream os = res.getOutputStream();
FileInputStream hFile = new FileInputStream(fileOut.getPath());
BufferedInputStream bis = new BufferedInputStream(hFile);
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=" + filename);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
bis.close();
log.info("【bis.close】");
if (os != null) {
log.info("【os is not null】");
try
{
os.close();
log.info("【os.close】");
} catch (IOException e) {
} finally {
os = null;
}
}
log.info("【printOutFile】:end");
}
private String[] createReport() throws IOException, SQLException {
String srcfile = "src.xlsx"; // マクロを含んだExcelBook
String destPath = "dist.xlsx";
String sheet = "log";
file[0] = destPath;
// 元ファイルからダウンロードファイルの生成
file_copy(srcfile, destPath);
FileInputStream fi=new FileInputStream(destPath);
XSSFWorkbook wb =new XSSFWorkbook(fi);
fi.close();
int row_index;
int col_index;
XSSFSheet sheet1 = wb.getSheet(sheet);
XSSFRow row = null;
XSSFCell cell;
// Excel出力
row_index = 0; // 先頭行
// TODO
// hg logでlogファイルを作成
// String log[]へlogファイルを読込み
for (int i = 0; i < log.length; i++) {
col_index = 1;
row = sheet1.createRow(row_index++);
cell = row.createCell(col_index++);
cell.setCellValue(log[i]);
}
FileOutputStream out = null;
out = new FileOutputStream(destPath);
wb.write(out);
out.close();
wb.close();
return file;
}
public void file_copy(String srcPath, String destPath) throws IOException {
log.info("file_copy()");
FileChannel srcChannel = new FileInputStream(srcPath).getChannel();
FileChannel destChannel = new FileOutputStream(destPath).getChannel();
try {
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
srcChannel.close();
destChannel.close();
}
}