2013-07-11 24 views
-1

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

我设法在过去创建了一些MS Excel工作簿,但是这看起来有些不同。我怎么能这样做?

由于提前,

gtludwig

+0

你可能有很大的运气尝试的许多例子之一是在Apache POI项目已在他们的网站 – epoch

回答

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(); 
+0

我要试试这个,谢谢!一旦我可以验证它是我需要的,我会接受答案。我可能会自我压抑! :) – gtludwig

+0

好吧,它的工作原理!但是,打开时,新文件始终是只读的,并且没有插入的数据。 – gtludwig

+0

在服务器端检查你的文件..他有数据...你在java中正确关闭文件? –

0

Excel支持普通的高原CSV格式,将您的数据导入CSV是simples方式IMO。如果文档中的格式比CSV可处理的格式复杂,则Office Automation可能是一种选择。 VBA足够强大的语言,您可以轻松操作Excel表格。 HTH