java webpoi 导出excel 2007_Java POI导入导出Excel文件-excel2007兼容包

这篇博客介绍了如何使用Java的POI库来实现Excel 2007文件的导入和导出。在导出部分,展示了如何创建带有标题的Excel文件并写入数据,同时提到了处理时间类型的注意事项。在导入部分,提供了文件上传的配置和处理方法,以及使用POI工具类从Excel文件中读取数据。
摘要由CSDN通过智能技术生成

Java POI Excel导入导出Excel文件

一、导入pom文件(版本号一定要相同,不然会报错)

<!--读取excel文件-->

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.17</version>

</dependency>

<!--导出excel文件-->

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.17</version>

</dependency>

二、实现导出功能

@RequestMapping("/outPutExcel")

public void outPutExcel(HttpServletResponse response) throws Exception {

// 每次写100行数据,就刷新数据出缓存

SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory,

Sheet sh = wb.createSheet();

// 这个是业务数据

List<TbClass> tmps = classService.getAllClass();

String[] titles = { "编号", "标题" };

Row row = sh.createRow(0);

// 第一行设置标题

for (int i = 0; i < titles.length; i++) {

String title = titles[i];

Cell cell1 = row.createCell(i);

cell1.setCellValue(title);

}

// 导出数据

for (int rowNum = 0; rowNum < tmps.size(); rowNum++) {

Row rowData = sh.createRow(rowNum + 1);

// TbClass 这个是我的业务类,这个是根据业务来进行填写数据

TbClass tmp = tmps.get(rowNum);

// 第一列

Cell cellDataA = rowData.createCell(0);

cellDataA.setCellValue(tmp.getcId());

// 第二列

Cell cellDataB = rowData.createCell(1);

cellDataB.setCellValue(tmp.getcName());

}

String fileName = "文件名称.xlsx";

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

wb.write(response.getOutputStream());

wb.close();

}

导出结果

9c542b27141c72640798d5d969483e87.png

导出时间类型

数据库使用时间类型,直接导出会出现以下这种情况。这个时候我们就需要处理一下时间类型。

1f8749570f66c4e220c54147f7f5bcea.png

用2种方法来解决时间转换字符串的方法

1、使用注解的方式

在属性类中添加注解属性类型就会转换成功啦,不过类型要改成String类型。(org.springframework.format.annotation 这个注解包是使用SpringMVC的类)

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

private String createTime;

2、使用时间转换类,就不复制代码啦。createTime 是时间类的一个属性。

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

if (null != tmp.getCreateTime())

cellDataC.setCellValue(df.format(tmp.getCreateTime()));

实体类(想了一下,还是把实体类放上来吧)

public class TbClass {

private Integer cId;

private String cName;

private String stuName;

private Timestamp createTime;

// 省略SetGet方法

}

af6be24394910077661644dd6d0cfb1f.png

二、实现导入功能

先画个图吧,这样我们按照图来走吧,让代码更加简单。

868a10cc7f4dc7446a13788c7289637e.png

公共的代码是和技术框架无关的,大家可以参考一下的,使用的是Spring+SpringMVC+Mybatis的技术框架。

Excel测试文件:

ba6607ee9239ce5d9d530544fa607b23.png

jsp页面:

<form name="Form2" action="fileUpload" method="post" enctype="multipart/form-data">

<input type="file" name="test">

<input type="submit" value="upload"/>

</form>

配置是有2种方式

xml文件中的配置:

<!-- 多部分文件上传 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="maxUploadSize" value="104857600" />

<property name="maxInMemorySize" value="4096" />

<property name="defaultEncoding" value="UTF-8"></property>

</bean>

在原始类中的配置:

@Bean

public CommonsMultipartResolver multipartResolver(DataSource dataSource) throws PropertyVetoException {

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();

multipartResolver.setDefaultEncoding("utf-8");

multipartResolver.setMaxUploadSize(10485760000L);

multipartResolver.setMaxInMemorySize(40960);

return multipartResolver;

}

Controller类(这里接收文件)

@ResponseBody

@RequestMapping(value = "/fileUpload", method = RequestMethod.POST, produces="text/html;charset=UTF-8")

public String fileUpload2(@RequestParam("test") CommonsMultipartFile test) throws Exception {

String path="E:/"+new Date().getTime()+test.getOriginalFilename();

File newFile=new File(path);

//通过CommonsMultipartFile的方法直接写文件(注意这个时候)

test.transferTo(newFile);

POIUtil.readExcel(path);

return "/success";

}

POIUtil工具类

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

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

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

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

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

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

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

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

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

import com.pojo.TbClass;

public class POIUtil {

public static void readExcel(String fileName) throws Exception {

InputStream is = new FileInputStream(new File(fileName));

Workbook hssfWorkbook = null;

if (fileName.endsWith("xlsx")) {

hssfWorkbook = new XSSFWorkbook(is);// Excel 2007

} else if (fileName.endsWith("xls")) {

hssfWorkbook = new HSSFWorkbook(is);// Excel 2003

}

// HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

// XSSFWorkbook hssfWorkbook = new XSSFWorkbook(is);

TbClass tbClass = null;

List<TbClass> list = new ArrayList<TbClass>();

// 循环工作表Sheet

for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {

// HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);

Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);

if (hssfSheet == null) {

continue;

}

// 循环行Row

for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {

Row hssfRow = hssfSheet.getRow(rowNum);

if (hssfRow != null) {

tbClass = new TbClass();

Cell cId = hssfRow.getCell(0);

Cell cName = hssfRow.getCell(1);

// 处理具体的业务数据,把业务数据装到List中

tbClass.setcId(Integer.parseInt(getStringValueFromCell(cId)));

tbClass.setcName(cName.toString());

list.add(tbClass);

}

}

}

// List中的数据就是在Excel中读取的内容

for (TbClass tbClass2 : list) {

// 在这里可以进行业务操作

System.out.println(tbClass2.getcId());

System.out.println(tbClass2.getcName());

}

}

public static String getStringValueFromCell(Cell cell) {

SimpleDateFormat sFormat = new SimpleDateFormat("MM/dd/yyyy");

DecimalFormat decimalFormat = new DecimalFormat("#.#");

String cellValue = "";

if(cell == null) {

return cellValue;

}

else if(cell.getCellType() == Cell.CELL_TYPE_STRING) {

cellValue = cell.getStringCellValue();

}

else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {

if(HSSFDateUtil.isCellDateFormatted(cell)) {

double d = cell.getNumericCellValue();

Date date = HSSFDateUtil.getJavaDate(d);

cellValue = sFormat.format(date);

}

else {

cellValue = decimalFormat.format((cell.getNumericCellValue()));

}

}

else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {

cellValue = "";

}

else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {

cellValue = String.valueOf(cell.getBooleanCellValue());

}

else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) {

cellValue = "";

}

else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {

cellValue = cell.getCellFormula().toString();

}

return cellValue;

}

}

运行结果:

cddbb5ff582b061678017c3d3bed947b.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值