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文件的读取与写入的更多相关文章

  1. java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

    需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --&g ...

  2. 使用POI 读取 Excel 文件,读取手机号码 变成 1.3471022771E10

    使用POI 读取 Excel 文件,读取手机号码 变成 1.3471022771E10 [问题点数:40分,结帖人xieyongqiu]             不显示删除回复             ...

  3. excel to datatable (c#用NPOI将excel文件内容读取到datatable数据表中)

    将excel文件内容读取到datatable数据表中,支持97-2003和2007两种版本的excel 1.第一种是根据excel文件路径读取excel并返回datatable /// <sum ...

  4. 条形码的应用三-----------从Excel文件中读取条形码

    条形码的应用三------从Excel文件中读取条形码 介绍 上一篇文章,我向大家展示了生成多个条形码并存储到Excel文件中的一个方法.后来我又有了个想法:既然条码插入到excel中了,我可不可以从 ...

  5. Java I/O---RandomAccessFile类(随机访问文件的读取和写入)

    1.JDK API中RandomAccessFile类的描述 此类的实例支持对随机访问文件的读取和写入.随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组.存在指向该隐含数组的光标或索引 ...

  6. 【asp.net】asp.net实现上传Excel文件并读取数据

    #前台代码:使用服务端控件实现上传 <form id="form1" runat="server"> <div> <asp:Fil ...

  7. 从Excel文件中读取内容

    从Excel文件中读取内容 global::System.Web.HttpPostedFileBase file = Request.Files["txtFile"]; strin ...

  8. Django框架(上传Excel文件并读取)

    博主今天整理下Django框架中上传Excel文件并读取 博主是要在管理平台中新增用例的维护功能,想着通过上传Excel文件来展示用例,下面是项目的路径图: 首先先建数据库模型 model.py 可以 ...

  9. 通过POI实现上传EXCEL的批量读取数据写入数据库

    最近公司新增功能要求导入excel,并读取其中数据批量写入数据库.于是就开始了这个事情,之前的文章,记录了上传文件,本篇记录如何通过POI读取excel数据并封装为对象上传. 上代码: 1.首先这是一 ...

随机推荐

  1. flask BytesIO() 多个文件打包下载 zipfile

    使用zipfile模块可以将多个文件打包成zip文件进行下载,但是常规的操作方式会在服务器磁盘上生成一个zip文件占用磁盘空间. 后引入BytesIO将文件写入到内存中然后下载: def dl_pla ...

  2. hdu2896 病毒肆虐【AC自动机】

    病毒侵袭 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...

  3. c++中inline函数的意义

    inline C++关键字,在函数声明或定义中函数返回类型前加上关键字inline,即可以把函数指定为内联函数.关键字inline必须与函数定义放在一起才能使函数成为内联,仅仅将inline放在函数声 ...

  4. POJ_3349_Snowflake Snow Snowflakes

    Snowflake Snow Snowflakes Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 43504   Accep ...

  5. Windows编程之connect函数研究

    写在前面:本博客为本人原创,严禁任何形式的转载!本博客只允许放在博客园(.cnblogs.com),如果您在其他网站看到这篇博文,请通过下面这个唯一的合法链接转到原文! 本博客全网唯一合法URL:ht ...

  6. RESTful URL设计指南(转)

    add by zhj: <RESTful Web Services Cookbook>这本书详细介绍了RESTFUL API的设计. 一般来说,一个好的URL,简单明了.这里有一个问题,对 ...

  7. 使用tagName定位报错

    使用标签进行定位元素,页面报错,由于input标签不唯一,webdriver默认会取第一个元素,但是第一个input元素的类型是‘hidden’,无法展示,因此程序就报错了 如何解决,未完待续...

  8. Word AddIn编译出现LINK2001 _main

        链接错误"unresolved external symbol _main" Article last modified on 2002-3-2 ------------- ...

  9. Improving the quality of the output

    There are a variety of reasons you might not get good quality output from Tesseract. It's important ...

  10. jmeter Bean Shell的使用(二)

    BeanShell的用法 在此介绍下BeanShell PreProcessor的用法,其它的beahshell可以类推.在此我们使用beahshell调用自己写的工具类,工具类实现了密码的加.解密功 ...