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();
}
导出结果
导出时间类型
数据库使用时间类型,直接导出会出现以下这种情况。这个时候我们就需要处理一下时间类型。
用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方法
}
二、实现导入功能
先画个图吧,这样我们按照图来走吧,让代码更加简单。
公共的代码是和技术框架无关的,大家可以参考一下的,使用的是Spring+SpringMVC+Mybatis的技术框架。
Excel测试文件:
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;
}
}
运行结果: