我需要加載模板MS Excel文件,將內容添加到某些單元格,然後通過用戶的瀏覽器下載,以便他可以打開和/或保存該文件。如何加載MS Excel文件,添加內容併發送給用戶?
我設法在過去創建了一些MS Excel工作簿,但是這看起來有些不同。我怎麼能這樣做?
由於提前,
gtludwig
我需要加載模板MS Excel文件,將內容添加到某些單元格,然後通過用戶的瀏覽器下載,以便他可以打開和/或保存該文件。如何加載MS Excel文件,添加內容併發送給用戶?
我設法在過去創建了一些MS Excel工作簿,但是這看起來有些不同。我怎麼能這樣做?
由於提前,
gtludwig
上有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
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();
Excel支持普通的高原CSV格式,將您的數據導入CSV是simples方式IMO。如果文檔中的格式比CSV可處理的格式複雜,則Office Automation可能是一種選擇。 VBA足夠強大的語言,您可以輕鬆操作Excel表格。 HTH
你可能有很大的運氣嘗試的許多例子之一是在Apache POI項目已在他們的網站 – epoch