天天看点

poi读取excel模板,填充内容并导出,支持导出2007支持公式自动计算

import java.io.file;

import java.io.fileinputstream;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.inputstream;

import org.apache.poi.hssf.usermodel.hssfcell;

import org.apache.poi.hssf.usermodel.hssfsheet;

import org.apache.poi.hssf.usermodel.hssfworkbook;

import org.apache.poi.poifs.filesystem.poifsfilesystem;

import org.apache.poi.xssf.usermodel.xssfcell;

import org.apache.poi.xssf.usermodel.xssfsheet;

import org.apache.poi.xssf.usermodel.xssfworkbook;

/**

* @author gerrard

* @discreption 根据已有的excel模板,修改模板内容生成新excel

*/

public class createexcel {

*

*(2003 xls后缀 导出)

* @param todo

* @return void 返回类型

* @author xsw

* @2016-12-7上午10:44:00

public static void createxls() throws ioexception{

//excel模板路径

file fi=new file("d:\\offer_template.xls");

poifsfilesystem fs = new poifsfilesystem(new fileinputstream(fi));

//读取excel模板

hssfworkbook wb = new hssfworkbook(fs);

//读取了模板内所有sheet内容

hssfsheet sheet = wb.getsheetat(0);

//如果这行没有了,整个公式都不会有自动计算的效果的

sheet.setforceformularecalculation(true);

//在相应的单元格进行赋值

hssfcell cell = sheet.getrow(11).getcell(6);//第11行 第6列

cell.setcellvalue(1);

hssfcell cell2 = sheet.getrow(11).getcell(7);

cell2.setcellvalue(2);

sheet.getrow(12).getcell(6).setcellvalue(12);

sheet.getrow(12).getcell(7).setcellvalue(12);

//修改模板内容导出新模板

fileoutputstream out = new fileoutputstream("d:/export.xls");

wb.write(out);

out.close();

}

*(2007 xlsx后缀 导出)

* @2016-12-7上午10:44:30

public static void createxlsx() throws ioexception{

file fi=new file("d:\\offer_template.xlsx");

inputstream in = new fileinputstream(fi);

xssfworkbook wb = new xssfworkbook(in);

xssfsheet sheet = wb.getsheetat(0);

xssfcell cell = sheet.getrow(11).getcell(6);//第11行 第6列

xssfcell cell2 = sheet.getrow(11).getcell(7);

fileoutputstream out = new fileoutputstream("d:/export.xlsx");

public static void main(string[] args) throws ioexception {

//excle 2003

createxls();

//excle 2007

createxlsx();

继续阅读