2013-07-11 18 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