apache POI技术的使用
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
下载开发包:
解压上面的zip文件:
在项目中引入POI的依赖:
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.11</version> </dependency>
POI使用:使用POI读取Excel的数据
package com.test.bos.test;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;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.junit.Test;public class POITest {@Testpublic void test() throws FileNotFoundException, IOException{String filePath = "E:\\区域导入测试数据.xls";//包装一个Excel文件对象HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(new File(filePath)));//读取文件中第一个Sheet标签页HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);//遍历标签页中所有的行for (Row row : sheetAt) {System.out.println();//换行//遍历行中的所有单元格for (Cell cell : row) {String value = cell.getStringCellValue();System.out.print(value);}}} }
POI结合OCUpload的使用
package com.test.bos.web.action;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List;import javax.annotation.Resource;import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller;import com.test.bos.domain.Region; import com.test.bos.service.IRegionService; import com.test.bos.web.action.base.BaseAction;/*** 区域管理* * @author jepson**/ @Controller("regionAction") @Scope("prototype") public class RegionAction extends BaseAction<Region> {@Resource(name="regionService")private IRegionService regionService;// 属性驱动,接收上传的文件private File regionFile;public void setRegionFile(File regionFile) {this.regionFile = regionFile;}List<Region> regionList = new ArrayList<Region>();/*** 区域导入* @throws IOException * @throws FileNotFoundException */public String importXls() throws Exception {//包装一个excel文件对象HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(regionFile));//读取文件中第一个sheet标签页HSSFSheet sheet = workbook.getSheet("Sheet1");//遍历页面中的每一行for (Row row : sheet) {int rowNum = row.getRowNum();//获取行号,从0开始if(rowNum==0){ //不需要第一行数据continue;//跳出本次循环 }String id = row.getCell(0).getStringCellValue();String province = row.getCell(1).getStringCellValue();String city = row.getCell(2).getStringCellValue();String district = row.getCell(3).getStringCellValue();String postcode = row.getCell(4).getStringCellValue();//包装一个区域对象Region region = new Region(id, province, city, district, postcode, null, null, null);/** 这里不建议使用* regionService.save(region);* 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数*/regionList.add(region);}//调用service层的方法批量保存 regionService.saveBatch(regionList);return NONE;} }
POI结合springmvc文件上传
@RequestMapping(value="/item/accountupload.action")public String accountAddBatchByUploadFile(HttpServletRequest request,HttpSession session,HttpServletResponse response, MultipartFile acountfile,Model model){List<Account> accountList = new ArrayList<Account>();try {//首先应该判断一下是否上传了文件if(!acountfile.isEmpty()){//获取上传的文件类型判断是否是一个xls格式的文件String contentType = acountfile.getContentType();if(!"application/vnd.ms-excel".equals(contentType)){model.addAttribute("uploadinfomsg", "你上传的文件类型不对");return "uploadinfo";}else{//上传的文件格式正确,使用poi技术读取excel表格的数据 InputStream inputStream = acountfile.getInputStream();//包装一个excel文件对象HSSFWorkbook workbook = new HSSFWorkbook(inputStream);//读取文件中第一个sheet标签页HSSFSheet sheet = workbook.getSheet("Sheet1");//获取登录用户的idInteger user_id = CommonUtils.getLoginUserId(session);//遍历页面中的每一行for (Row row : sheet) {int rowNum = row.getRowNum();//获取行号,从0开始if(rowNum==0){ //不需要第一行数据continue;//跳出本次循环 }String website = row.getCell(1).getStringCellValue();String url = row.getCell(2).getStringCellValue();String account = row.getCell(3).getStringCellValue();String username = row.getCell(4).getStringCellValue();String mail = row.getCell(5).getStringCellValue();//这里需要判断一下表格的类型//0表示是double类型的,1表示String类型String telephone = null;if(row.getCell(6).getCellType()==0){Double tele = row.getCell(6).getNumericCellValue();telephone = tele.toString();}else{ telephone = row.getCell(6).getStringCellValue();}//这里需要判断一下表格的类型//0表示是double类型的,1表示String类型String hint = null;if(row.getCell(7).getCellType()==0){Double h = row.getCell(7).getNumericCellValue();hint = h.toString();}else{hint = row.getCell(7).getStringCellValue();}//包装一个账户对象Account ac = new Account(website, url, account, username, mail, telephone, hint, user_id);/** 这里不建议使用* itemService.save(ac);* 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数*/accountList.add(ac);}//调用service层的方法批量保存 itemService.saveBatch(accountList);model.addAttribute("uploadinfomsg", "恭喜你上传成功");return "uploadinfo";}}else{model.addAttribute("uploadinfomsg", "你没有选择上传的文件");return "uploadinfo";}} catch (Exception e) {e.printStackTrace();}model.addAttribute("uploadinfomsg", "上传失败");return "uploadinfo";}
使用POI将数据写到Excel文件中
/*** 分区数据导出功能* @throws IOException */public String exportXls() throws IOException{//第一步:查询所有的分区数据List<Subarea> list = subareaService.findAll();//第二步:使用POI将数据写到Excel文件中//在内存中创建一个Excel文件HSSFWorkbook workbook = new HSSFWorkbook();//创建一个标签页HSSFSheet sheet = workbook.createSheet("分区数据");//创建标题行HSSFRow headRow = sheet.createRow(0);headRow.createCell(0).setCellValue("分区编号");headRow.createCell(1).setCellValue("开始编号");headRow.createCell(2).setCellValue("结束编号");headRow.createCell(3).setCellValue("位置信息");headRow.createCell(4).setCellValue("省市区");//遍历list集合for (Subarea subarea : list) {HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);dataRow.createCell(0).setCellValue(subarea.getId());dataRow.createCell(1).setCellValue(subarea.getStartnum());dataRow.createCell(2).setCellValue(subarea.getEndnum());dataRow.createCell(3).setCellValue(subarea.getPosition());dataRow.createCell(4).setCellValue(subarea.getRegion().getName());}//第三步:使用输出流进行文件下载(一个流、两个头) String filename = "分区数据.xls";String contentType = ServletActionContext.getServletContext().getMimeType(filename);ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();ServletActionContext.getResponse().setContentType(contentType);//获取客户端浏览器类型String agent = ServletActionContext.getRequest().getHeader("User-Agent");filename = FileUtils.encodeDownloadFilename(filename, agent);ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+filename);workbook.write(out);return NONE;}
解决下载文件不同浏览器附件名的编码
package cn.itcast.bos.utils;import java.io.IOException; import java.net.URLEncoder;import sun.misc.BASE64Encoder;public class FileUtils {/*** 下载文件时,针对不同浏览器,进行附件名的编码* * @param filename* 下载文件名* @param agent* 客户端浏览器* @return 编码后的下载附件名* @throws IOException*/public static String encodeDownloadFilename(String filename, String agent)throws IOException {if (agent.contains("Firefox")) { // 火狐浏览器filename = "=?UTF-8?B?"+ new BASE64Encoder().encode(filename.getBytes("utf-8"))+ "?=";filename = filename.replaceAll("\r\n", "");} else { // IE及其他浏览器filename = URLEncoder.encode(filename, "utf-8");filename = filename.replace("+"," ");}return filename;} }
使用POI将数据写到Excel中
@RequestMapping(value="/item/downloadaccount.action")public String downloadAccount(QueryVo vo,Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{Integer userId = CommonUtils.getLoginUserId(session);vo.setUserId(userId); // 设置当前登录用户的id//查询登录用户的所有account信息List<Account> accountList = itemService.QueryAccountList(vo);//在内存中创建一个Excel文件HSSFWorkbook workbook = new HSSFWorkbook();//创建一个标签页HSSFSheet sheet = workbook.createSheet("Sheet1");//创建标题行HSSFRow headRow = sheet.createRow(0);headRow.createCell(0).setCellValue("account_id");headRow.createCell(1).setCellValue("website");headRow.createCell(2).setCellValue("url");headRow.createCell(3).setCellValue("account");headRow.createCell(4).setCellValue("username");headRow.createCell(5).setCellValue("mail");headRow.createCell(6).setCellValue("telephone");headRow.createCell(7).setCellValue("hint");//遍历list集合for (Account ac : accountList) {HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);dataRow.createCell(0).setCellValue(ac.getId());dataRow.createCell(1).setCellValue(ac.getWebsite());dataRow.createCell(2).setCellValue(ac.getUrl());dataRow.createCell(3).setCellValue(ac.getAccount());dataRow.createCell(4).setCellValue(ac.getUsername());dataRow.createCell(5).setCellValue(ac.getMail());dataRow.createCell(6).setCellValue(ac.getTelephone());dataRow.createCell(7).setCellValue(ac.getHint());}//使用输出流进行文件下载(一个流、两个头) String filename = "account.xls";String contentType =request.getServletContext().getMimeType(filename);ServletOutputStream out = response.getOutputStream();response.setContentType(contentType);//获取客户端浏览器类型String agent = request.getHeader("User-Agent");filename = this.encodeDownloadFilename(filename, agent);response.setHeader("content-disposition", "attachment;filename="+filename);workbook.write(out);return null;}/*** 下载文件时,针对不同浏览器,进行附件名的编码* * @param filename* 下载文件名* @param agent* 客户端浏览器* @return 编码后的下载附件名* @throws IOException*/private String encodeDownloadFilename(String filename, String agent)throws IOException {if (agent.contains("Firefox")) { // 火狐浏览器filename = "=?UTF-8?B?"+ new BASE64Encoder().encode(filename.getBytes("utf-8"))+ "?=";filename = filename.replaceAll("\r\n", "");} else { // IE及其他浏览器filename = URLEncoder.encode(filename, "utf-8");filename = filename.replace("+"," ");}return filename;}
转载于:https://www.cnblogs.com/jepson6669/p/8855521.html
apache POI技术的使用相关推荐
- java 显示word文档_如何通过apache POI技术来读取Word文档,并把Word文档的原来格式完整地显示在html网页?...
我把代码发到你的邮箱. package com.my.util; import java.io.BufferedWriter; import java.io.File; import java.io. ...
- java excel相同的合并_java servlet导出EXCEL并合并EXCEL相同值的单元格(Apache POI技术)...
@ResponseBody @RequestMapping(params = "method=loadOutExcel") public void loadOutExcel(Htt ...
- poi excel mysql_java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 :java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 : ...
- SpringBoot图文教程9—SpringBoot 导入导出 Excel 「Apache Poi」(亲测)
有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 来源:Springboot使用POI实现导出Excel文件示例的搜索结果-阿里云开 ...
- 使用POI技术简单的将数据库中的数据读取出为Excel文件
利用POI生成.xlxs 效果图 利用反射将实体类的属性读取出来,然后对应数据库表中的字段,循环插入对应的数据 数据来源 本次测试的数据为数据库查询得出,所以需要MyBatis查询数据库,然后根据反射 ...
- apache poi斜边框线_如何使用Apache POI在Excel单元格内画斜线(Java)
需求背景: 在使用Apache POI进行表格数据导出时,某些单元格需要画上斜线. 1.需求背景 解决方法: 国内相关文章较少,于是在国外技术网站上找了一圈,最终在StackOverFlow上找到了方 ...
- java导入excel数据到mysql_java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : 项目结构: Excel中的测试数据: 数据库结构: 对应的SQL: 1 CREATE TABL ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- sql2java-excel(二):基于apache poi实现数据库表的导出的spring web支持
sql2java是我几年年开始写的一个sql2java是一个轻量级数据库(SQL)访问代码(java)生成器.这几年一直在根据工作需要维护升级,最近的项目中需要对数据库的记录提供导出excel的功能. ...
- sql2java-excel(一):基于apache poi实现数据库表的导出及支持spring web
sql2java是我几年年开始写的一个sql2java是一个轻量级数据库(SQL)访问代码(java)生成器.这几年一直在根据工作需要维护升级,最近的项目中需要对数据库的记录提供导出excel的功能. ...
最新文章
- 分类问题的评估指标(Evaluation for Classifier)
- linux 全局搜索文件_Linux笔记之文件搜索1
- CentOS7.2下配置SOCKS5代理
- 10 个最酷的 Linux 单行命令
- Mybatis 单独项目
- 视频播放时,关键帧丢失时造成的透明水影现象
- flutter 加载gif图片
- 数学建模计算机部分知识,数学建模计算机知识的应用
- 〖Python 数据库开发实战 - MySQL篇㉕〗- 数据更新操作 - UPDATE 语句
- WinCap数据包显示
- [单片机框架][DFU] Dfu升级例子 带crc校验+超时机制+led指示灯+芯片加锁+芯片自擦
- 【Python实例学习】用Python的xlsxwriter模块操作Excel表格,包括写入数据、样式设置、插入图片等
- linux上运行gfortran,linux下gfortran 生成so文件
- 【AI应用】NVIDIA GeForce RTX 3060的详情参数
- 从初试北京211到走上调剂的坎坷考研路
- 【雷达通信】基于matlab距离角度解耦法MIMO-OFDM雷达波束形成【含Matlab源码 2208期】
- 125 · 背包问题(二)Backpack II
- 如何快速在一段字符串中提取想要的字符
- json解析到map
- 网站域名被拦截,网站被流量劫持,该怎么做?