POI按照模版导出Excel数据

POI按照模版导出Excel数据

一、所需jar包

二、ExportExcelUtil.java

package com.upsoft.exportexcel;



import java.io.FileInputStream;

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;

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

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

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

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



public class ExportExcelUtil {



public static void main(String[] args) throws Exception {



ExportExcelUtil export = new ExportExcelUtil();

String srcFilePath = "d:/人员信息模板.xlsx";

String fileName = "test_" + System.currentTimeMillis() + ".xlsx";

String desFilePath = "d:/" + fileName;



export.exportExcel(srcFilePath,desFilePath);

}



//根据指定的excel模板导出数据

public void exportExcel(String srcFilePath,String desFilePath) throws Exception {



//创建Excel文件的输入流对象

FileInputStream fis = new FileInputStream(srcFilePath);

//根据模板创建excel工作簿

XSSFWorkbook workBook = new XSSFWorkbook(fis);

//创建Excel文件输出流对象

FileOutputStream fos = new FileOutputStream(desFilePath);

//获取创建的工作簿第一页

XSSFSheet sheet = workBook.getSheetAt(0);

//给指定的sheet命名

workBook.setSheetName(0,"2016-11-30"); 



//修改标题

XSSFRow row = sheet.getRow(0);

XSSFCell cell = row.getCell(0);

//获取指定单元格值

String s = cell.getStringCellValue();

cell.setCellValue("修改后的标题为:"+s);



//获取当前sheet最后一行数据对应的行索引

int currentLastRowIndex = sheet.getLastRowNum();

int newRowIndex = currentLastRowIndex + 1;

XSSFRow newRow = sheet.createRow(newRowIndex);

//开始创建并设置该行每一单元格的信息,该行单元格的索引从 0 开始

int cellIndex = 0;



//创建一个单元格,设置其内的数据格式为字符串,并填充内容,其余单元格类同

XSSFCell newNameCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_STRING);

newNameCell.setCellValue("乔玉宝");

XSSFCell newGenderCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_STRING);

newGenderCell.setCellValue("男");

XSSFCell newAgeCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_NUMERIC);

newAgeCell.setCellValue(25);

XSSFCell newAddressCell = newRow.createCell(cellIndex++, Cell.CELL_TYPE_NUMERIC);

newAddressCell.setCellValue("重庆市渝北区");



workBook.write(fos);



//关闭流

fis.close();

fos.flush();

fos.close();

System.out.println("导出成功");

}

}

三、结果

1、模版Excel

 

 

2、导出数据后的Excel

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值