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 {
- @Test
- public 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");
- //获取登录用户的id
- Integer 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;
- }
apache POI技术的使用的更多相关文章
- java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...
- java的poi技术写Excel的Sheet
在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...
- java的poi技术读,写Excel[2003-2007,2010]
在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- Apache POI 一键上传(导入excel文件到数据库)
import cn.XXXX.bos.utils.PinYin4jUtils; import org.apache.commons.lang3.StringUtils; // HSSF:操作07版本之 ...
- java的poi技术读取和导入Excel实例
本篇文章主要介绍了java的poi技术读取和导入Excel实例,报表输出是Java应用开发中经常涉及的内容,有需要的可以了解一下. 报表输出是Java应用开发中经常涉及的内容,而一般的报表往往缺乏通用 ...
- java的poi技术读取Excel数据
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- Java导出数据行写入到Excel表格:基于Apache POI
Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...
- java poi技术读取到数据库
https://www.cnblogs.com/hongten/p/java_poi_excel.html java的poi技术读取Excel数据到MySQL 这篇blog是介绍java中的poi技术 ...
随机推荐
- 导出Excel多个表多个sheet
protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); ...
- APP 市场需求网址
http://mi.talkingdata.com/terminals.html?terminalType=4
- Python-第三方库requests详解(附requests中文官方教程)
转自http://blog.csdn.net/cyjs1988/article/details/73294774 Python+requests中文官方教程: http://www.python-re ...
- Mac下配置MAMP Pro+PHPStorm
一.配置MAMP Pro Hosts 下载地址:http://xclient.info/s/mamp-pro.html 在Hosts页签下,如图所示位置选择你工程目录 二.配置PHPStorm 1.点 ...
- easyui rowspan
第一种写法 columns: [ [ { field: 'depName', title: '部门', rowspan: 2, width: '100px', align: 'center' }, { ...
- Powershell Deploy Service Fabric Application To Local Cluster
之前写过一篇用 Powershell 部署 Service Fabric Application 到本地集群的随笔,感觉过程有点复杂,这次将流程简化,只需要将应用程序打包,加上配置文件就可以了. ...
- 在FooterTemplate内显示DropDownList控件
如果想在Gridview控件FooterTemplate内显示DropDownList控件供用户添加数据时所应用.有两种方法可以实现,一种是在GridView控件的OnRowDataBound事件中写 ...
- 网易CentOS yum源
wget http://mirrors.163.com/.help/CentOS6-Base-163.repo
- Shell学习日记
if语句的使用 if语句的的格式: if [ expression ] expression 和方括号([ ])之间必须有空格,否则会有语法错误. then statments fi 或者: if [ ...
- Django / Python 链接MySQL数据库
https://www.cnblogs.com/wupeiqi/articles/5237704.html python (Django)中使用MySQL 首先python3中没有 MySQLdb 需 ...