POI Excel文件的读取与写入
1. 创建目录
if(!(new File(path).isDirectory())){
new File(path).mkdirs();
}
2. 读取Excel文件,并进行写入操作
Workbook workbook = new HSSFWorkbook(new FileInputStream(path+filename));
Sheet sourceSheet = workbook.getSheetAt(0);
int rowEnd = sourceSheet.getLastRowNum();
for (int i = 0; i <= rowEnd; i++) {//按 行 读取
Row row = sourceSheet.getRow(i);
//读取
String str=row.getCell(n).getStringCellValue();//n表示第几列
//写入
row.createCell(m, Cell.CELL_TYPE_STRING).setCellValue(nbFile.getProductId().toString());//m表示第几列
}
FileOutputStream out=new FileOutputStream(WebConstants.FILE.UPLOAD_PATH + nbFile.getUserId() + "/" + nbFile.getFilename());
out.flush();
workbook.write(out);
out.close();
3. 写入Excel文件
HSSFWorkbook resultWorkbook=new HSSFWorkbook();
HSSFSheet resultSheet =resultWorkbook.createSheet("sheet1"); for(int i=0;i<100;i++){
Row row=resultSheet.createRow(i);
row.createCell(n, Cell.CELL_TYPE_STRING).setCellValue(trans.getName());//n表示第几列
}
FileOutputStream out=new FileOutputStream(path+filename+".xls"); //向d://test.xls中写数据
out.flush();
resultWorkbook.write(out);
out.close();
4. maven项目引入POI包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
5. 例子
package cn.*.*.quartz; import org.apache.poi.hssf.usermodel.HSSFSheet;
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 java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List; @Component
public class BatchQuery {
private final static Log logger = LogFactory.getLog(BatchQuery.class); @Autowired
private HandleFileService handleFileService;
@Autowired
private CheckService checkService;
private String path="D://excel/"
@Scheduled(cron="${batch.query.frequency}")
public void query() {
try {
List<NbFile> fileList = handleFileService.getNbFile();
logger.info("batchQuery number="+fileList.size());
if (fileList != null && fileList.size() > 0) {
for (file1 File: fileList) {
if(!(new File(path).isDirectory())){
new File(path).mkdirs();
}
//结果文件
HSSFWorkbook resultWorkbook=new HSSFWorkbook();
HSSFSheet resultSheet =resultWorkbook.createSheet("sheet1");
//客户请求文件
Workbook workbook = new HSSFWorkbook(new FileInputStream(path+ file1.getFilename()));
Sheet sourceSheet = workbook.getSheetAt(0);
int rowEnd = sourceSheet.getLastRowNum();
//边读取Excel文件,边写入结果,写入已读记录
for (int i = 0; i <= rowEnd; i++) {//按 行 读取
Row row = sourceSheet.getRow(i);
Trans trans=queryByProduct(row,file1.getProductId(),file1.getUserId());
if (null!=trans){//有结果
//把查询结果添加入新的Excel文件
addResultToExcel(resultWorkbook,resultSheet,trans, i,file1);
//标志该条记录已查
addQueryFlag(workbook,row, file1);
}
}
handleFileService.delete(nbFile);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} //每查询一条记录,在该记录后面添加已查询的标志
private void addQueryFlag(Workbook workbook,Row row,NbFile nbFile)throws Exception{
row.createCell(WebConstants.PP_CELLINDEX.STATE, Cell.CELL_TYPE_STRING).setCellValue(nbFile.getProductId().toString());
FileOutputStream out=new FileOutputStream(WebConstants.FILE.UPLOAD_PATH + nbFile.getUserId() + "/" + nbFile.getFilename());
out.flush();
workbook.write(out);
out.close();
} //把查询信息 写入 Excel文件中
private void addResultToExcel(Workbook resultWorkbook,HSSFSheet resultSheet,Trans trans,int i,NbFile nbFile)throws Exception {
Row row=resultSheet.createRow(i);
row.createCell(WebConstants.PP_CELLINDEX.NAME, Cell.CELL_TYPE_STRING).setCellValue(trans.getName());
row.createCell(WebConstants.PP_CELLINDEX.IDCARD, Cell.CELL_TYPE_STRING).setCellValue(trans.getIdcard());
row.createCell(WebConstants.PP_CELLINDEX.PHONE, Cell.CELL_TYPE_STRING).setCellValue(trans.getPhone());
row.createCell(WebConstants.PP_CELLINDEX.BANKCARD, Cell.CELL_TYPE_STRING).setCellValue(trans.getBankcard());
row.createCell(WebConstants.PP_CELLINDEX.CPHM, Cell.CELL_TYPE_STRING).setCellValue(trans.getCphm());
row.createCell(WebConstants.PP_CELLINDEX.CLLX, Cell.CELL_TYPE_STRING).setCellValue(trans.getCllx());
row.createCell(WebConstants.PP_CELLINDEX.DABH, Cell.CELL_TYPE_STRING).setCellValue(trans.getDabh());
row.createCell(WebConstants.PP_CELLINDEX.JSZH, Cell.CELL_TYPE_STRING).setCellValue(trans.getJszh());
JSONObject json=JSONObject.parseObject(trans.getResultJSON());
row.createCell(WebConstants.PP_CELLINDEX.RESULTCODE, Cell.CELL_TYPE_STRING).setCellValue(json.getString("resultCode"));
row.createCell(WebConstants.PP_CELLINDEX.RESULTMESSAGE, Cell.CELL_TYPE_STRING).setCellValue(json.getString("resultMessage"));
FileOutputStream out=new FileOutputStream(WebConstants.FILE.RESULT_PATH+nbFile.getUserId()+"_"+WebConstants.ProductEnum.nameFromId(nbFile.getProductId())+".xls"); //向d://test.xls中写数据
out.flush();
resultWorkbook.write(out);
out.close();
} //查询结果
private Trans queryByProduct(Row row,Integer productId,Integer userId)throws Exception{
if (null==row.getCell(WebConstants.PP_CELLINDEX.STATE)||!productId.toString().equals(row.getCell(WebConstants.PP_CELLINDEX.STATE).getStringCellValue())){
Trans trans=new Trans();
trans.setProductId(productId);
trans.setUserId(userId);
trans.setName(row.getCell(WebConstants.PP_CELLINDEX.NAME) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.NAME).getStringCellValue());
trans.setIdcard(row.getCell(WebConstants.PP_CELLINDEX.IDCARD) == null ? null:row.getCell(WebConstants.PP_CELLINDEX.IDCARD).getStringCellValue());
trans.setPhone(row.getCell(WebConstants.PP_CELLINDEX.PHONE) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.PHONE).getStringCellValue());
trans.setBankcard(row.getCell(WebConstants.PP_CELLINDEX.BANKCARD) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.BANKCARD).getStringCellValue());
trans.setCphm(row.getCell(WebConstants.PP_CELLINDEX.CPHM) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.CPHM).getStringCellValue());
trans.setCllx(row.getCell(WebConstants.PP_CELLINDEX.CLLX) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.CLLX).getStringCellValue());
trans.setJszh(row.getCell(WebConstants.PP_CELLINDEX.JSZH) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.JSZH).getStringCellValue());
trans.setDabh(row.getCell(WebConstants.PP_CELLINDEX.DABH) == null ? null : row.getCell(WebConstants.PP_CELLINDEX.DABH).getStringCellValue());
String result=checkService.check(trans);
if (!StringUtil.isEmpty(result)){
trans.setResultJSON(result);
}else {
return null;
}
return trans;
}
return null;
}
}
POI Excel文件的读取与写入的更多相关文章
- java使用POI实现excel文件的读取,兼容后缀名xls和xlsx
需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --&g ...
- 使用POI 读取 Excel 文件,读取手机号码 变成 1.3471022771E10
使用POI 读取 Excel 文件,读取手机号码 变成 1.3471022771E10 [问题点数:40分,结帖人xieyongqiu] 不显示删除回复 ...
- excel to datatable (c#用NPOI将excel文件内容读取到datatable数据表中)
将excel文件内容读取到datatable数据表中,支持97-2003和2007两种版本的excel 1.第一种是根据excel文件路径读取excel并返回datatable /// <sum ...
- 条形码的应用三-----------从Excel文件中读取条形码
条形码的应用三------从Excel文件中读取条形码 介绍 上一篇文章,我向大家展示了生成多个条形码并存储到Excel文件中的一个方法.后来我又有了个想法:既然条码插入到excel中了,我可不可以从 ...
- Java I/O---RandomAccessFile类(随机访问文件的读取和写入)
1.JDK API中RandomAccessFile类的描述 此类的实例支持对随机访问文件的读取和写入.随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组.存在指向该隐含数组的光标或索引 ...
- 【asp.net】asp.net实现上传Excel文件并读取数据
#前台代码:使用服务端控件实现上传 <form id="form1" runat="server"> <div> <asp:Fil ...
- 从Excel文件中读取内容
从Excel文件中读取内容 global::System.Web.HttpPostedFileBase file = Request.Files["txtFile"]; strin ...
- Django框架(上传Excel文件并读取)
博主今天整理下Django框架中上传Excel文件并读取 博主是要在管理平台中新增用例的维护功能,想着通过上传Excel文件来展示用例,下面是项目的路径图: 首先先建数据库模型 model.py 可以 ...
- 通过POI实现上传EXCEL的批量读取数据写入数据库
最近公司新增功能要求导入excel,并读取其中数据批量写入数据库.于是就开始了这个事情,之前的文章,记录了上传文件,本篇记录如何通过POI读取excel数据并封装为对象上传. 上代码: 1.首先这是一 ...
随机推荐
- Accelerated Failure Time Models加速失效时间模型AFT
Weibull distribution 或者 σ是未知的scale参数,独立于X的常量, σ>0 是服从某一分布的随机变量 残差(residuals)=
- 8.23 js
2018-8-23 15:12:05 js 参考 :https://www.cnblogs.com/liwenzhou/p/8011504.html 2018-8-23 20:56:29 上面js的东 ...
- 这个代码给所有带有name属性的链接加了一个背景色
jQuery起点教程之使用选择器和事件jQuery提供两种方式来选择html的elements: 第一种是用CSS和Xpath选择器联合起来形成一个字符串来传送到jQuery的构造器(如:$(&quo ...
- ubuntu16.04下笔记本电脑扩展双屏安装过程
想给笔记本电脑外界一个显示屏,因为科研需要,我的笔记本是windows10加Ubuntu16.04双系统,主要使用Ubuntu系统. 首先是硬件 一个外置显示屏是必须的了,然后我的笔电上只有HDMI接 ...
- 《MYSQL必知必会》
1. 同一个数据库中不允许出现同名表:不同的数据库中可以出现同名表2. 每一行记录都用有一个key(一列或一组列作为key)3. 作为key的列不允许值为空(NULL)4. 多个列作为key时,多个列 ...
- 设置tabBar中间的按钮比较大的发布
MainTabBarController.h UITabBarItem *item = [self.tabBar.items objectAtIndex:index]; [item setTitle: ...
- 2018/03/31 每日一个Linux命令 之 date
date 命令主要用于查看和修改时间和时区 -- 这里主要学习基本的查看和设置时间和时区的方法. 直接显示日期 date '+%D' 效果 vagrant@hong:~$ date '+%D' 03/ ...
- sass和css的calc运算
1.sass不识别不同单位之间的计算,而calc则没问题. width: #{1rem - 2px}; /*出错*/ width: calc(1rem - 2px); 通常情况定制css样式,我不需要 ...
- sql server 备份恢复效率
sql server 备份恢复效率 如何提高备份的速度呢? 其实这个问题和如何让系统跑的更快是一样的,要想系统跑的更快,无非就是:优化系统,或者就是更好更强大的服务器,特别是更多的cpu.更大的内存. ...
- vue学习七之Axios
JQuery时代,我们使用ajax向后台提交数据请求,Vue时代,Axios提供了前端对后台数据请求的各种方式. 什么是Axios Axios是基于Promise的Http客户端,可以在浏览器和nod ...