-1

我需要加载模板 MS Excel 文件,将内容添加到某些单元格,然后通过用户的浏览器下载,以便他可以打开和/或保存文件。

我过去设法创建了一些 MS Excel 工作簿,但这似乎有些不同。我怎么能做到?

提前致谢,

特鲁德维希

4

2 回答 2

0

Excel 支持普通 plat CSV 格式,将数据插入 CSV 是 IMO 最简单的方式。如果您的文档中存在 CSV 无法处理的复杂格式,Office Automation 可能是一个选择。VBA 语言足够强大,您可以轻松操作 Excel 表格。高温高压

于 2013-07-11T13:50:39.450 回答
0

在他们的官方网站上有关于 apache-poi 的很好的教程

final Workbook wb;
fileIn =new FileInputStream(fname);
wb = WorkbookFactory.create(fileIn);//opening a file
final Sheet sheet = wb.createsheet("Report");// create a sheet

然后使用RowCell类在单元格中添加内容

Row row;
Cell cell;
row=sheet.getRow(0); //get existing row
if(row==null)
row=sheet.createRow(0);//if row not present create row
cell=row.getCell(0);
if(cell==null)
cell=row.createCell(0);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(0);//set cell value

更新:我忘了提到你需要在文件上写内容

fout=new FileOutputStream(fname);
wb.write(fout);

然后在finally块中关闭 fout

if(fout!=null)
fout.close();

完成 excel 文件后,创建一个下载 servlet

File file=new File(fname);
FileInputStream fis=new FileInputStream(file);

        response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition",
                             "attachment;filename="+fname+".xlsm");
            ServletContext ctx = getServletContext();
            InputStream input = new BufferedInputStream(new FileInputStream(file), 1024 * 10);
            OutputStream output = new BufferedOutputStream(response.getOutputStream(), 1024 * 10);

            byte[] buffer = new byte[1024 * 10];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        output.flush();
        output.close();
        input.close();
        fis.close();
于 2013-07-11T13:58:28.083 回答