Excel的读入与写出(所有方法都可以写在一个工具类)
需要的依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 文件上传jar -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
1.从程序中写出到excel
/**
* excel title 也是excel表格的首行
*/
public static String[] excelTitle() {
String[] strArray = { "订单号", "订单状态", "业务类型","流水号" ,"更新时间", "产品名称", "订单项状态", "产品类型" };
return strArray;
}
/**
* 创建excel读取数据到指定目录下
*/
public static String writeExcel(List<Map> dataList, int cloumnCount,String finalXlsxPath){
OutputStream out = null;
try {
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("sheet1");
sheet.setDefaultColumnWidth(20);// 默认列宽
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row1 = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
// 创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 添加excel title
HSSFCell cell = null;
String[] strArray=excelTitle();
for (int i = 0; i < strArray.length; i++) {
cell = row1.createCell(i);
cell.setCellValue(strArray[i]);
cell.setCellStyle(style);
}
/**
* 往Excel中写新数据
*/
for (int j = 0; j < dataList.size(); j++) {
// 创建一行:从第二行开始,跳过属性列
Row row = sheet.createRow(j + 1);
// 得到要插入的每一条记录
// 得到要插入的每一条记录
Map dataMap = dataList.get(j);
String sourceOrderNbr = dataMap.get("sourceOrderNbr").toString();
String statusCdName = dataMap.get("statusCdName").toString();
String sceneTypeName = dataMap.get("sceneTypeName").toString();
String custOrderNbr = dataMap.get("custOrderNbr").toString();
String updateDate = dataMap.get("updateDate").toString();
String applyObjSpecName = dataMap.get("applyObjSpecName").toString();
String statusCdName1 = dataMap.get("statusCdName1").toString();
String serviceOfferName = dataMap.get("serviceOfferName").toString();
for (int k = 0; k <= cloumnCount; k++) {
// 在一行内循环
Cell first = row.createCell(0);
first.setCellValue(sourceOrderNbr);
Cell second = row.createCell(1);
second.setCellValue(statusCdName);
Cell third = row.createCell(2);
third.setCellValue(sceneTypeName);
Cell c3 = row.createCell(3);
c3.setCellValue(custOrderNbr);
Cell c4 = row.createCell(4);
c4.setCellValue(updateDate);
Cell c5 = row.createCell(5);
c5.setCellValue(applyObjSpecName);
Cell c6 = row.createCell(6);
c6.setCellValue(statusCdName1);
Cell c7 = row.createCell(7);
c7.setCellValue(serviceOfferName);
}
}
// 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
/* SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateTime = simpleDateFormat.format(new Date());
response.setContentType("application/vnd.ms-excel");
//设置下载文件名,attachment和filename之间是分号,注意!
response.addHeader("Content-Disposition", "attachment;filename="+"OrderList"+dateTime+".xls");
out = response.getOutputStream();
wb.write(out);*/
out = new FileOutputStream(finalXlsxPath);
wb.write(out);
} catch (Exception e) {
e.printStackTrace();
return "另一个程序正在使用此文件,进程无法访问";
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("数据导出成功");
return "success";
}
2.从excel表格读取数据(借鉴前辈的代码)
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException{
//检查文件 调用下面的方法
checkFile(file);
//获得Workbook工作薄对象 调用下面的方法
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}