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.首先这是一 ...
随机推荐
- 关于python爬虫的编码错误
现在才发现很多错误只有自己一点点的去尝试才能发现.不管之前别人怎么和你说,总是不可能面面俱到,所以提升自己的方法就是亲手实践,自己一点点的去发现问题,并一个个的解决.慢慢享受其中无言的快感. 今天就发 ...
- Jenkins构建报错(Jenkins is reserved for jobs with matching label expression)解决办法
Jenkins构建报错Jenkins is reserved for jobs with matching label expression 原因节点配置导致 修改配置
- 【转】jQuery之前端国际化jQuery.i18n.properties
jQuery之前端国际化jQuery.i18n.properties 基于jQuery.i18n.properties 实现前端页面的资源国际化 jquery-i18n-properties
- JavaScript之Function 和 Object 的区别和联系
1.先看一个控制台的输出: instanceof 运算符字面意思是 左边是右边的一个实例吗? 但是这两条输出让人很困惑.Function 是 Object 的实例.Object 也是 Function ...
- 2018/03/14 每日一个Linux命令 之 ln
ln 链接命令 -- 类似Windows的快捷方式,实际等于建立了一个文件同步的链接,我想,MAC上面复制一个文件到另一个路径,特别快,它可能就是建立了一个链接. -- 在通俗点讲,就是你创建链接之后 ...
- java实现树状图
1.定义测试数据类 VirtualDataGenerator: import java.util.ArrayList;import java.util.HashMap;import java.util ...
- 使用LinkedList模拟栈数据结构的集合
封装MyStack类 public class MyStack { private LinkedList link; //调用MyStack创建对象的时候其实是调用的LinkedList创建的是Lin ...
- hdu3339In Action(最短路+01背包)
http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=259#problem/H Description Since 1945, whe ...
- 【Cocos2dx 3.3】图片裁剪
从一个图片集中裁剪出需要的图片时,采用的坐标是屏幕坐标系: 示例如下: 图片:res/Images/grossini_dance_atlas.png ,每个人物大小为85* ...
- [LeetCode] 42. Trapping Rain Water_hard tag: Two Pointers
Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...