Java POI汇入汇出Excel档案
Java POI Excel汇入汇出Excel档案
一、汇入pom档案(版本号一定要相同,不然会报错)
org.apache.poi
poi
3.17
org.apache.poi
poi-ooxml
3.17
二、实现汇出功能
@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 tmps = classService.getAllClass();
String[] titles = { "编号", "标题" };
Row row = sh.createRow(0);
// 第一行设定标题
for (int i = 0; i
String title = titles[i];
Cell cell1 = row.createCell(i);
cell1.setCellValue(title);
}
// 汇出资料
for (int rowNum = 0; 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页面:
配置是有2种方式
xml档案中的配置:
在原始类中的配置:
@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 list = new ArrayList();
// 循环工作表Sheet
for (int numSheet = 0; numSheet
// HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; 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;
}
}
执行结果:

