excel表格界面导入功能实现,及实现过程中遇见的问题

/**
 * 督导结果数据导入
 * @param file 导入excel文件实体
 * @param request
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping(value="/surveyDataImport.html",method={RequestMethod.POST},produces= "text/html;charset=UTF-8")
public@ResponseBody String surveyDataImport(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpSession session,HttpServletResponse response) throws Exception{
InputStream is = null;
Workbook workbook = null;
String returnStr = "";
JSONObject jsonObj = new JSONObject();
String fileName = "";
boolean flag = false;
try {
if(file != null){
fileName = file.getOriginalFilename();
}else{
jsonObj.put("status", -1);
jsonObj.put("msg", "请选择文件在上传...");
return jsonObj.toString();
}
//高版本excel文件处理
is = file.getInputStream();
workbook = new XSSFWorkbook(is);
flag = true;
} catch (Exception e) {
if(workbook == null){//低版本excel文件处理
is = file.getInputStream();
workbook = new HSSFWorkbook(is);
flag = true;
}
}finally{
if(!flag || workbook == null){
jsonObj.put("status", -1);
jsonObj.put("msg", "该上传文件解析失败,请选择重新上传...");
return jsonObj.toString(); 
}
if(is != null){
is.close();
}
}
logger.info("该excel文件【"+ fileName +"】数据开始导入,请稍等...");
returnStr = serveyDataImportService. eduSurveyDataImport(workbook, fileName);
return returnStr;

}

public String eduSurveyDataImport(Workbook workbook, String fileName){
//根据项目名称判断数据文件数据是否重复导入
int beginIndex = fileName.indexOf("“");
int endIndex = fileName.indexOf("”");
String itemName = fileName.substring(beginIndex + 1, endIndex);
JSONObject jsonObj = new JSONObject();
List<EduSurveyMain>eduSurveyMainList = eduSurveyMainDao.getEduSurveyMainbyItemName(itemName);
if(eduSurveyMainList != null && eduSurveyMainList.size() > 0){
jsonObj.put("status", -1);
jsonObj.put("msg", "该文件内容已经导过,请勿重复添加...");
return jsonObj.toString();
}
//1.将excel数据处理并保存到edu_survey_detail_log表中
List<EduSurveyDetailLog> surveyLogList = excelData2DetailList(workbook);
boolean importFlag = false;
try{
importFlag = eduSurveyDetailLogDao.saveLog(surveyLogList);
if(importFlag){
//2.如果数据保存成功,开始掉存储过程
String procedureName = "bianmin.edu_survey";
boolean callFlag = eduSurveyDetailLogDao.callProcedure(procedureName);
if(callFlag){
jsonObj.put("status", 1);
jsonObj.put("msg", "该调查结果文件【"+ fileName +"】数据导入成功!");
logger.info("文件【"+fileName+"】数据导入完毕!");
}else{
jsonObj.put("status", -1);
jsonObj.put("msg", "存储过程调用失败!");
}
}else{
jsonObj.put("status", -1);
jsonObj.put("msg", "该调查结果文件【"+ fileName +"】数据保存edu_survey_detail_log表失败!");
}
}finally{
//3.清理edu_survey_detail_log表中所有数据
eduSurveyDetailLogDao.clearLogData();
}
return jsonObj.toString();
}

当时解析excel我们使用的组件是poi,而非jxl。因为poi支持更高版本的excel 处理。实现excel导入功能过程还比较顺利,只是在读取excel时出现了点问题。简述如下:


刚开始使用new HSSFWorkbook(new FileInputStream(excelFile))来读取Workbook,对Excel2003以前(包括2003)的版本没有问题,但读取Excel2007时发生如下异常: 
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) 
        该错误意思是说,文件中的数据是用Office2007+XML保存的,而现在却调用OLE2 Office文档处理,应该使用POI不同的部分来处理这些数据,比如使用XSSF来代替HSSF。 
        于是按提示使用XSSF代替HSSF,用new XSSFWorkbook(excelFile)来读取Workbook,对Excel2007没有问题了,可是在读取Excel2003以前(包括2003)的版本时却发生了如下新异常: 
org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: '*.xls' 
        该错误是说,操作无效,不能打开指定的xls文件。 
        下载POI的源码后进行单步调试,发现刚开始的时候还是对的,但到ZipFile类后就找不到文件了,到网上查了下,原来是XSSF不能读取Excel2003以前(包括2003)的版本,这样的话,就需要在读取前判断文件是2003前的版本还是2007的版本,然后对应调用HSSF或XSSF来读取。 

小结:由于HSSFWorkbook只能操作excel2003一下版本,XSSFWorkbook只能操作excel2007以上版本,所以利用Workbook接口创建对应的对象操作excel来处理兼容性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是实现VueExcel表格批量导入功能,并携带公共的模型id的步骤: 1. 安装`xlsx`和`file-saver`库 ```bash npm install xlsx file-saver --save ``` 2. 创建一个Excel表格导入组件 ```vue <template> <div> <input type="file" ref="file" @change="importExcel" /> </div> </template> <script> import XLSX from 'xlsx' import { saveAs } from 'file-saver' export default { props: { modelId: { type: String, required: true } }, methods: { importExcel(e) { const files = e.target.files const promises = [] for (let i = 0; i < files.length; i++) { const file = files[i] const promise = new Promise((resolve, reject) => { const reader = new FileReader() reader.onload = (event) => { const data = event.target.result const workbook = XLSX.read(data, { type: 'binary' }) const worksheet = workbook.Sheets[workbook.SheetNames[0]] const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) // 发送请求,并携带公共的模型id // ... resolve() } reader.readAsBinaryString(file) }) promises.push(promise) } Promise.all(promises).then(() => { // 所有文件导入完成后的回调 }) } } } </script> ``` 3. 在`importExcel`方法,使用`FileReader`读取Excel表格文件,并使用`XLSX`库解析数据。然后,您可以将解析后的数据发送到后端,同时携带公共的模型id。注意,这里使用了Promise.all来处理多个文件的导入。 4. 在父组件使用Excel表格导入组件,并向其传递公共的模型id。 ```vue <template> <div> <excel-import :model-id="modelId" /> </div> </template> <script> import ExcelImport from './ExcelImport.vue' export default { components: { ExcelImport }, data() { return { modelId: '123456' // 公共的模型id } } } </script> ``` 这样,您就可以在Vue实现Excel表格批量导入功能,并携带公共的模型id。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值