JAVA:Excel导入导出详解(2)--导入
程序员文章站
2022-07-13 14:32:43
...
1. 浏览文件夹,选择需要上传的文件
代码
jsp
<li class="col-sm-1">
<span>上 传:</span>
</li>
<li class="col-sm-3">
<span>
<input type="file" id="upfile" name="upfile" placeholder=""/>
</span>
</li>
<li class="col-sm-2">
<button onclick="importExp();" class="btn btn-success btn-sm ">导 入</button>
<span>格式:.xls</span>
</li>
js
//导入文件
function importExp() {
var formData = new FormData();
var name = $("#upfile").val();
formData.append("file", $("#upfile")[0].files[0]);
formData.append("name", name);
$.ajax({
url: '/manage/order/upload',
type: 'POST',
async: false,
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
beforeSend: function () {
console.log("正在进行,请稍候");
},
success: function (responseStr) {
if (responseStr != "0") {
alert("导入成功" + responseStr + "条数据!");
} else {
alert("导入失败");
}
}
});
}
注意
2. 将本地文件上传至服务器指定位置
代码
/**
* 上传文件
*
* @param
* @return
*/
@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public String importExp(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String realPath = request.getRealPath("");
String filePath = realPath + "/upload/upload.xls";
int resmsg = 0;
// 判断文件是否为空
if (!file.isEmpty()) {
Integer rowCount = 1000;
Integer columnCount = 8;
try {
deleteFile(filePath);
// 转存文件
file.transferTo(new File(filePath));
File fileNew = new File(filePath);
List<ExcelSheetPO> list = readExcel(fileNew, rowCount, columnCount);
System.out.println(list);
resmsg = manualOrder(list.get(0).getDataList());
} catch (Exception e) {
e.printStackTrace();
}
}
return (resmsg + "");
}
注意
路径获取,可使用 String realPath = request.getRealPath("");
获取root的路径,在拼出file的路径。
3. 服务器解析Excel文件
ExcelUtil代码
package com.jy.util.excelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
//import com.zkingsoft.common.tools.FileUtil;
/**
* Created by SchonZhang on 2018/10/19 0019.
* excel工具类 提供读取和写入excel的功能
*
*/
public class ExcelUtil {
/**
* 标题样式
*/
private final static String STYLE_HEADER = "header";
/**
* 表头样式
*/
private final static String STYLE_TITLE = "title";
/**
* 数据样式
*/
private final static String STYLE_DATA = "data";
/**
* 存储样式
*/
private static final HashMap<String, CellStyle> cellStyleMap = new HashMap<>();
/**
* 读取excel文件里面的内容 支持日期,数字,字符,函数公式,布尔类型
* @param file
* @param rowCount
* @param columnCount
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static List<ExcelSheetPO> readExcel(File file, Integer rowCount, Integer columnCount)
throws FileNotFoundException, IOException {
// 根据后缀名称判断excel的版本
// String extName = FileUtil.getFileExtName(file);
String extName = "."+FilenameUtils.getExtension(file.getName());
Workbook wb = null;
if (ExcelVersion.V2003.getSuffix().equals(extName)) {
wb = new HSSFWorkbook(new FileInputStream(file));
} else if (ExcelVersion.V2007.getSuffix().equals(extName)) {
wb = new XSSFWorkbook(new FileInputStream(file));
} else {
// 无效后缀名称,这里之能保证excel的后缀名称,不能保证文件类型正确,不过没关系,在创建Workbook的时候会校验文件格式
throw new IllegalArgumentException("Invalid excel version");
}
// 开始读取数据
List<ExcelSheetPO> sheetPOs = new ArrayList<>();
// 解析sheet
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
List<List<Object>> dataList = new ArrayList<>();
//合并单元格处理,获取合并行
List<CellRangeAddress> cras = getCombineCell(sheet);
ExcelSheetPO sheetPO = new ExcelSheetPO();
sheetPO.setSheetName(sheet.getSheetName());
sheetPO.setDataList(dataList);
int readRowCount = 0;
if (rowCount == null || rowCount > sheet.getPhysicalNumberOfRows()) {
readRowCount = sheet.getPhysicalNumberOfRows();
} else {
readRowCount = rowCount;
}
// 解析sheet 的行
for (int j = sheet.getFirstRowNum(); j < readRowCount; j++) {
//判断是否为合并行
if(isMergedRegion(sheet,j,0)){
int lastRow = getRowNum(cras,sheet.getRow(i).getCell(0),sheet);
for(;j<=lastRow;j++){
Row row = sheet.getRow(j);
if (row == null) {
continue;
}
if (row.getFirstCellNum() < 0) {
continue;
}
int readColumnCount = 0;
if (columnCount == null || columnCount > row.getLastCellNum()) {
readColumnCount = (int) row.getLastCellNum();
} else {
readColumnCount = columnCount;
}
List<Object> rowValue = new LinkedList<Object>();
// 解析sheet 的列
for (int k = 0; k < readColumnCount; k++) {
// if(isMergedRegion(sheet,j,k)) {
// rowValue.add(getMergedRegionValue(sheet, j, k));
// }else{
// Cell cell = row.getCell(k);
// rowValue.add(getCellValue(wb, cell));
// }
//不取合并单元格的数值
Cell cell = row.getCell(k);
rowValue.add(getCellValue(wb, cell));
}
dataList.add(rowValue);
}
j--;
}else{
Row row = sheet.getRow(j);
if (row == null) {
continue;
}
if (row.getFirstCellNum() < 0) {
continue;
}
int readColumnCount = 0;
if (columnCount == null || columnCount > row.getLastCellNum()) {
readColumnCount = (int) row.getLastCellNum();
} else {
readColumnCount = columnCount;
}
List<Object> rowValue = new LinkedList<Object>();
// 解析sheet 的列
for (int k = 0; k < readColumnCount; k++) {
Cell cell = row.getCell(k);
rowValue.add(getCellValue(wb, cell));
}
dataList.add(rowValue);
}
}
sheetPOs.add(sheetPO);
}
return sheetPOs;
}
private static Object getCellValue(Workbook wb, Cell cell) {
Object columnValue = null;
if (cell != null) {
DecimalFormat df = new DecimalFormat("0");// 格式化 number
// String
// 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
columnValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
columnValue = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
columnValue = nf.format(cell.getNumericCellValue());
} else {
columnValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}
break;
case Cell.CELL_TYPE_BOOLEAN:
columnValue = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
columnValue = "#";
break;
case Cell.CELL_TYPE_FORMULA:
// 格式单元格
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateFormulaCell(cell);
CellValue cellValue = evaluator.evaluate(cell);
columnValue = cellValue.getNumberValue();
break;
default:
columnValue = cell.toString();
}
}
return columnValue;
}
/**
* 在硬盘上写入excel文件
* @param version
* @param excelSheets
* @param filePath
* @throws IOException
*/
public static void createWorkbookAtDisk(ExcelVersion version, List<ExcelSheetPO> excelSheets, String filePath)
throws IOException {
FileOutputStream fileOut = new FileOutputStream(filePath);
createWorkbookAtOutStream(version, excelSheets, fileOut, true);
}
/**
* 把excel表格写入输出流中,输出流会被关闭
* @param version
* @param excelSheets
* @param outStream
* @param closeStream
* 是否关闭输出流
* @throws IOException
*/
public static void createWorkbookAtOutStream(ExcelVersion version, List<ExcelSheetPO> excelSheets,
OutputStream outStream, boolean closeStream) throws IOException {
if (CollectionUtils.isNotEmpty(excelSheets)) {
Workbook wb = createWorkBook(version, excelSheets);
wb.write(outStream);
if (closeStream) {
outStream.close();
}
}
}
private static Workbook createWorkBook(ExcelVersion version, List<ExcelSheetPO> excelSheets) {
Workbook wb = createWorkbook(version);
for (int i = 0; i < excelSheets.size(); i++) {
ExcelSheetPO excelSheetPO = excelSheets.get(i);
if (excelSheetPO.getSheetName() == null) {
excelSheetPO.setSheetName("sheet" + i);
}
// 过滤特殊字符
Sheet tempSheet = wb.createSheet(WorkbookUtil.createSafeSheetName(excelSheetPO.getSheetName()));
buildSheetData(wb, tempSheet, excelSheetPO, version);
}
return wb;
}
private static void buildSheetData(Workbook wb, Sheet sheet, ExcelSheetPO excelSheetPO, ExcelVersion version) {
sheet.setDefaultRowHeight((short) 400);
sheet.setDefaultColumnWidth((short) 30);
createTitle(sheet, excelSheetPO, wb, version);
createHeader(sheet, excelSheetPO, wb, version);
createBody(sheet, excelSheetPO, wb, version);
}
private static void createBody(Sheet sheet, ExcelSheetPO excelSheetPO, Workbook wb, ExcelVersion version) {
List<List<Object>> dataList = excelSheetPO.getDataList();
for (int i = 0; i < dataList.size() && i < version.getMaxRow(); i++) {
List<Object> values = dataList.get(i);
Row row = sheet.createRow(2 + i);
for (int j = 0; j < values.size() && j < version.getMaxColumn(); j++) {
Cell cell = row.createCell(j);
cell.getCellStyle().cloneStyleFrom(getStyle(STYLE_DATA, wb));
if(values.get(j)!=null){
cell.setCellValue(values.get(j).toString());
}
}
}
}
private static void createHeader(Sheet sheet, ExcelSheetPO excelSheetPO, Workbook wb, ExcelVersion version) {
String[] headers = excelSheetPO.getHeaders();
Row row = sheet.createRow(1);
for (int i = 0; i < headers.length && i < version.getMaxColumn(); i++) {
Cell cellHeader = row.createCell(i);
cellHeader.getCellStyle().cloneStyleFrom(getStyle(STYLE_HEADER, wb));
cellHeader.setCellValue(headers[i]);
}
}
private static void createTitle(Sheet sheet, ExcelSheetPO excelSheetPO, Workbook wb, ExcelVersion version) {
Row titleRow = sheet.createRow(0);
Cell titleCel = titleRow.createCell(0);
titleCel.setCellValue(excelSheetPO.getTitle());
// titleCel.setCellStyle(getStyle(STYLE_TITLE, wb));
titleCel.getCellStyle().cloneStyleFrom(getStyle(STYLE_TITLE, wb));
// 限制最大列数
int column = excelSheetPO.getDataList().size() > version.getMaxColumn() ? version.getMaxColumn()
: excelSheetPO.getDataList().size();
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, column ));
}
private static CellStyle getStyle(String type, Workbook wb) {
if (cellStyleMap.containsKey(type)) {
return cellStyleMap.get(type);
}
// 生成一个样式
CellStyle style = wb.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setWrapText(true);
if (STYLE_HEADER == type) {
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
Font font = wb.createFont();
font.setFontHeightInPoints((short) 16);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
} else if (STYLE_TITLE == type) {
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
Font font = wb.createFont();
font.setFontHeightInPoints((short) 18);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
} else if (STYLE_DATA == type) {
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
Font font = wb.createFont();
font.setFontHeightInPoints((short) 12);
style.setFont(font);
}
cellStyleMap.put(type, style);
return style;
}
private static Workbook createWorkbook(ExcelVersion version) {
switch (version) {
case V2003:
return new HSSFWorkbook();
case V2007:
return new XSSFWorkbook();
}
return null;
}
/**
* 获取单元格的值
* @param cell
* @return
*/
public static String getCellValue(Cell cell){
if(cell == null) return "";
if(cell.getCellType() == Cell.CELL_TYPE_STRING){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
return String.valueOf(cell.getBooleanCellValue());
}else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA){
return cell.getCellFormula() ;
}else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
return String.valueOf(cell.getNumericCellValue());
}
return "";
}
/**
* 合并单元格处理,获取合并行
* @param sheet
* @return List<CellRangeAddress>
*/
public static List<CellRangeAddress> getCombineCell(Sheet sheet)
{
List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
//获得一个 sheet 中合并单元格的数量
int sheetmergerCount = sheet.getNumMergedRegions();
//遍历所有的合并单元格
for(int i = 0; i<sheetmergerCount;i++)
{
//获得合并单元格保存进list中
CellRangeAddress ca = sheet.getMergedRegion(i);
list.add(ca);
}
return list;
}
//获得合并单元格的起始行, 结束行
private static int getRowNum(List<CellRangeAddress> listCombineCell, Cell cell, Sheet sheet){
int xr = 0;
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for(CellRangeAddress ca:listCombineCell)
{
//获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if(cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR)
{
if(cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC)
{
xr = lastR;
}
}
}
return lastR;
// return xr;
}
/**
* 判断单元格是否为合并单元格,是的话则将单元格的值返回
* @param listCombineCell 存放合并单元格的list
* @param cell 需要判断的单元格
* @param sheet sheet
* @return
*/
public String isCombineCell(List<CellRangeAddress> listCombineCell,Cell cell,Sheet sheet)
throws Exception{
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
String cellValue = null;
for(CellRangeAddress ca:listCombineCell)
{
//获得合并单元格的起始行, 结束行, 起始列, 结束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if(cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR)
{
if(cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC)
{
Row fRow = sheet.getRow(firstR);
Cell fCell = fRow.getCell(firstC);
cellValue = getCellValue(fCell);
break;
}
}
else
{
cellValue = "";
}
}
return cellValue;
}
/**
* 获取合并单元格的值
* @param sheet
* @param row
* @param column
* @return
*/
public static String getMergedRegionValue(Sheet sheet, int row, int column){
int sheetMergeCount = sheet.getNumMergedRegions();
for(int i = 0 ; i < sheetMergeCount ; i++){
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if(row >= firstRow && row <= lastRow){
if(column >= firstColumn && column <= lastColumn){
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell) ;
}
}
}
return null ;
}
/**
* 判断指定的单元格是否是合并单元格
* @param sheet
* @param row 行下标
* @param column 列下标
* @return
*/
private static boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if(row >= firstRow && row <= lastRow){
if(column >= firstColumn && column <= lastColumn){
return true;
}
}
}
return false;
}
}
ExcelSheetPO代码
package com.jy.util.excelUtil;
/**
* Created by SchonZhang on 2018/10/19 0019.
*/
import java.util.List;
/**
* 定义表格的数据对象
*/
public class ExcelSheetPO {
/**
* sheet的名称
*/
private String sheetName;
/**
* 表格标题
*/
private String title;
/**
* 头部标题集合
*/
private String[] headers;
/**
* 数据集合
*/
private List<List<Object>> dataList;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String[] getHeaders() {
return headers;
}
public void setHeaders(String[] headers) {
this.headers = headers;
}
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
}
ExcelVersion代码
package com.jy.util.excelUtil;
/**
* Created by SchonZhang on 2018/10/19 0019.
*/
/**
* excel版本枚举
*
*/
public enum ExcelVersion {
/**
* 虽然V2007版本支持最大支持1048575 * 16383 ,
* V2003版支持65535*255
* 但是在实际应用中如果使用如此庞大的对象集合会导致内存溢出,
* 因此这里限制最大为10000*100,如果还要加大建议先通过单元测试进行性能测试。
* 1000*100 全部导出预计时间为27s左右
*/
V2003(".xls", 10000, 7), V2007(".xlsx", 100, 100);
private String suffix;
private int maxRow;
private int maxColumn;
ExcelVersion(String suffix, int maxRow, int maxColumn) {
this.suffix = suffix;
this.maxRow = maxRow;
this.maxColumn = maxColumn;
}
public String getSuffix() {
return this.suffix;
}
public int getMaxRow() {
return maxRow;
}
public void setMaxRow(int maxRow) {
this.maxRow = maxRow;
}
public int getMaxColumn() {
return maxColumn;
}
public void setMaxColumn(int maxColumn) {
this.maxColumn = maxColumn;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
注意
- FilenameUtils:需引入import org.apache.commons.io.FilenameUtils;
- 格式xls V2003 对应HSSFWorkbook
- 格式xlsl V2007对应XSSFWorkbook
- 本代码支持对合并单元格的处理,若不需要,可删除
4. 将Excel中解析的数据存入数据库中
代码
/**
* 将解析出的数据存入数据库
* @param list
* @return
*/
public int manualOrder(List<List<Object>> list) {
boolean flag = true;
Long userId = 1L;
Calendar currentDate = Calendar.getInstance();
DdOrderVo ddOrderVo = null;
int successOrder = 0;
Long mainorderNum = this.getOrdercode(userId);
Long orderNum = this.getOrdercode(userId);
try {
//产生新订单///////////////////////////////////////////////////////////////////////
for (List<Object> excelSheetPO : list) {
ddOrderVo = new DdOrderVo();
ddOrderVo.setOrderType(2);
// ddOrderVo.setOuterOrderNum(structurizationTrade.getFullOrderInfo().getOrderInfo().getTid());
//插入订单商品表
//根据商品名称获得商品id////
DdGoodsVo ddGoodsVo = new DdGoodsVo();
//判断数据是否满足8个都对应
if (excelSheetPO.size() < 8) {
continue;
}
ddGoodsVo.setName(excelSheetPO.get(6) + "");
ddGoodsVo = ddGoodsService.findById(ddGoodsVo);
if (ddGoodsVo == null) {
continue;
}
DdOrderGoodsVo orderGoodsVo = new DdOrderGoodsVo();
orderGoodsVo.setGoodsName(ddGoodsVo.getName());
orderGoodsVo.setGoodsId(ddGoodsVo != null ? ddGoodsVo.getId() : 0);
String goodsNum = excelSheetPO.get(7).toString();
orderGoodsVo.setGoodsNum((int) Double.parseDouble((goodsNum)));
orderGoodsVo.setGoodsState(Short.parseShort("5"));
orderGoodsVo.setUserId(userId);
Object o = excelSheetPO.get(0);
if (o.toString() != "#" || excelSheetPO.get(0) != "#") {
mainorderNum = this.getOrdercode(userId);
orderNum = this.getOrdercode(userId);
//生成订单////////////////////////////////////////////
ddOrderVo = new DdOrderVo();
ddOrderVo.setMainorderNum(mainorderNum);
ddOrderVo.setOrderNum(orderNum);
ddOrderVo.setOrderState(1);
ddOrderVo.setOrderType(2);
ddOrderVo.setOrderTime(DateUtil.getTimestamp());
ddOrderVo.setUserId(userId);
ddOrderService.insert(ddOrderVo);
//生成订单发货地址/////////////////////////////////////////
SysAddressVo sysAddressVo = new SysAddressVo();
sysAddressVo.setUserid(ddOrderVo.getId());
sysAddressVo.setAddressee((excelSheetPO.get(0) + ""));
sysAddressVo.setPhone((excelSheetPO.get(5) + ""));
sysAddressVo.setProvince((excelSheetPO.get(1) + ""));
sysAddressVo.setCity((excelSheetPO.get(2) + ""));
sysAddressVo.setDistrict((excelSheetPO.get(3) + ""));
sysAddressVo.setAddress((excelSheetPO.get(4) + ""));
sysAddressService.insert(sysAddressVo);
}
orderGoodsVo.setOrderNum(orderNum);
ddOrderGoodsService.insert(orderGoodsVo);
successOrder++;
}
} catch (Exception e) {
e.printStackTrace();
}
return successOrder;
}
注意
- 注意处理一个订单多个商品即excel中合并单元格的处理。
上一篇: PHP生成两个sheet的excel
下一篇: Notification简介(转)