利用模板生成excel
对于格式比较固定的数据结构,我们有时只需要修改单元格中的数据,没有增删需求的,最简单的方法就是使用模板,这样可以节省我们很多的时间去设置样式.
我用的是poi3.15版本的jar包.最新的是3.16.
最为最简单的例子,只是建了一个简单的java工程.
首先需要导入所依赖的jar包,下载地址http://poi.apache.org/download.html#POI-3.15.
然后需要自己先建立一个已经设置样式的excel文件.简单格式如下:
package mjdai.testmodel; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @author mjdai * @Discreption 根据已有的Excel模板,修改模板内容生成新Excel 这个类知识修改excel中的内容 */ public class CreateExcel1 { public static void main(String[] args) throws IOException { // excel模板路径 D:\temp\excelTest File file = new File("D:/temp/excelTest/temple.xlsx"); // 读取excel模板 InputStream is = new FileInputStream(file); // 获取工作薄,此处注意2003和2007稍有不同,本次以2007为例. XSSFWorkbook wb = new XSSFWorkbook(is); // 读取了模板内所有sheet内容,获取第一个sheet页为getSheetAt(0) // 获取第二个getSheetAt(1)依此类推 XSSFSheet sheet = wb.getSheetAt(0); // 在相应的单元格进行赋 // 注意:getRow(i)和getCell(0)都必须是模板中已经赋值了的,否则会包空指针异常. for (int i = 1; i < 7; i++) { XSSFCell cell = sheet.getRow(i).getCell(0); cell.setCellValue("姓名" + i); XSSFCell cell1 = sheet.getRow(i).getCell(1); cell1.setCellValue("班级" + i); XSSFCell cell2 = sheet.getRow(i).getCell(2); cell2.setCellValue("年龄" + i); XSSFCell cell3 = sheet.getRow(i).getCell(3); cell3.setCellValue("住址" + i); XSSFCell cell4 = sheet.getRow(i).getCell(4); cell4.setCellValue("联系人" + i); XSSFCell cell5 = sheet.getRow(i).getCell(5); cell5.setCellValue("联系电话" + i); } // 输出到指定的磁盘 FileOutputStream out = new FileOutputStream( "D:/temp/excelTest/export.xlsx"); wb.write(out); out.close(); } }
这个只是修改excel中的内容.


浙公网安备 33010602011771号