Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

下载开发包:

解压上面的zip文件:

在项目中引入POI的依赖:

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.11</version>
  5. </dependency>

POI使用:使用POI读取Excel的数据

  1. package com.test.bos.test;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7.  
  8. import org.apache.poi.hssf.usermodel.HSSFSheet;
  9. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  10. import org.apache.poi.ss.usermodel.Cell;
  11. import org.apache.poi.ss.usermodel.Row;
  12. import org.junit.Test;
  13.  
  14. public class POITest {
  15.  
  16. @Test
  17. public void test() throws FileNotFoundException, IOException{
  18. String filePath = "E:\\区域导入测试数据.xls";
  19. //包装一个Excel文件对象
  20. HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(new File(filePath)));
  21. //读取文件中第一个Sheet标签页
  22. HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
  23. //遍历标签页中所有的行
  24. for (Row row : sheetAt) {
  25. System.out.println();//换行
  26. //遍历行中的所有单元格
  27. for (Cell cell : row) {
  28. String value = cell.getStringCellValue();
  29. System.out.print(value);
  30. }
  31. }
  32. }
  33. }

POI结合OCUpload的使用

  1. package com.test.bos.web.action;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. import javax.annotation.Resource;
  11.  
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  14. import org.apache.poi.ss.usermodel.Row;
  15. import org.springframework.context.annotation.Scope;
  16. import org.springframework.stereotype.Controller;
  17.  
  18. import com.test.bos.domain.Region;
  19. import com.test.bos.service.IRegionService;
  20. import com.test.bos.web.action.base.BaseAction;
  21.  
  22. /**
  23. * 区域管理
  24. *
  25. * @author jepson
  26. *
  27. */
  28. @Controller("regionAction")
  29. @Scope("prototype")
  30. public class RegionAction extends BaseAction<Region> {
  31. @Resource(name="regionService")
  32. private IRegionService regionService;
  33. // 属性驱动,接收上传的文件
  34. private File regionFile;
  35.  
  36. public void setRegionFile(File regionFile) {
  37. this.regionFile = regionFile;
  38. }
  39.  
  40. List<Region> regionList = new ArrayList<Region>();
  41. /**
  42. * 区域导入
  43. * @throws IOException
  44. * @throws FileNotFoundException
  45. */
  46. public String importXls() throws Exception {
  47. //包装一个excel文件对象
  48. HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(regionFile));
  49. //读取文件中第一个sheet标签页
  50. HSSFSheet sheet = workbook.getSheet("Sheet1");
  51. //遍历页面中的每一行
  52. for (Row row : sheet) {
  53. int rowNum = row.getRowNum();//获取行号,从0开始
  54. if(rowNum==0){ //不需要第一行数据
  55. continue;//跳出本次循环
  56. }
  57. String id = row.getCell(0).getStringCellValue();
  58. String province = row.getCell(1).getStringCellValue();
  59. String city = row.getCell(2).getStringCellValue();
  60. String district = row.getCell(3).getStringCellValue();
  61. String postcode = row.getCell(4).getStringCellValue();
  62.  
  63. //包装一个区域对象
  64. Region region = new Region(id, province, city, district, postcode, null, null, null);
  65. /*
  66. * 这里不建议使用
  67. * regionService.save(region);
  68. * 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数
  69. */
  70. regionList.add(region);
  71. }
  72. //调用service层的方法批量保存
  73. regionService.saveBatch(regionList);
  74. return NONE;
  75. }
  76. }

POI结合springmvc文件上传

  1. @RequestMapping(value="/item/accountupload.action")
  2. public String accountAddBatchByUploadFile(HttpServletRequest request,HttpSession session,
  3. HttpServletResponse response, MultipartFile acountfile,Model model){
  4.  
  5. List<Account> accountList = new ArrayList<Account>();
  6. try {
  7. //首先应该判断一下是否上传了文件
  8. if(!acountfile.isEmpty()){
  9. //获取上传的文件类型判断是否是一个xls格式的文件
  10. String contentType = acountfile.getContentType();
  11. if(!"application/vnd.ms-excel".equals(contentType)){
  12. model.addAttribute("uploadinfomsg", "你上传的文件类型不对");
  13. return "uploadinfo";
  14. }else{
  15. //上传的文件格式正确,使用poi技术读取excel表格的数据
  16.  
  17. InputStream inputStream = acountfile.getInputStream();
  18. //包装一个excel文件对象
  19. HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
  20.  
  21. //读取文件中第一个sheet标签页
  22. HSSFSheet sheet = workbook.getSheet("Sheet1");
  23.  
  24. //获取登录用户的id
  25. Integer user_id = CommonUtils.getLoginUserId(session);
  26.  
  27. //遍历页面中的每一行
  28. for (Row row : sheet) {
  29. int rowNum = row.getRowNum();//获取行号,从0开始
  30. if(rowNum==0){ //不需要第一行数据
  31. continue;//跳出本次循环
  32. }
  33.  
  34. String website = row.getCell(1).getStringCellValue();
  35. String url = row.getCell(2).getStringCellValue();
  36.  
  37. String account = row.getCell(3).getStringCellValue();
  38. String username = row.getCell(4).getStringCellValue();
  39.  
  40. String mail = row.getCell(5).getStringCellValue();
  41.  
  42. //这里需要判断一下表格的类型
  43. //0表示是double类型的,1表示String类型
  44. String telephone = null;
  45. if(row.getCell(6).getCellType()==0){
  46. Double tele = row.getCell(6).getNumericCellValue();
  47. telephone = tele.toString();
  48. }else{
  49. telephone = row.getCell(6).getStringCellValue();
  50. }
  51.  
  52. //这里需要判断一下表格的类型
  53. //0表示是double类型的,1表示String类型
  54. String hint = null;
  55. if(row.getCell(7).getCellType()==0){
  56. Double h = row.getCell(7).getNumericCellValue();
  57. hint = h.toString();
  58. }else{
  59. hint = row.getCell(7).getStringCellValue();
  60. }
  61.  
  62. //包装一个账户对象
  63. Account ac = new Account(website, url, account, username, mail, telephone, hint, user_id);
  64.  
  65. /*
  66. * 这里不建议使用
  67. * itemService.save(ac);
  68. * 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数
  69. */
  70. accountList.add(ac);
  71. }
  72. //调用service层的方法批量保存
  73. itemService.saveBatch(accountList);
  74. model.addAttribute("uploadinfomsg", "恭喜你上传成功");
  75. return "uploadinfo";
  76. }
  77. }else{
  78. model.addAttribute("uploadinfomsg", "你没有选择上传的文件");
  79. return "uploadinfo";
  80. }
  81.  
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. }
  85. model.addAttribute("uploadinfomsg", "上传失败");
  86. return "uploadinfo";
  87. }

使用POI将数据写到Excel文件中

  1.   /**
  2. * 分区数据导出功能
  3. * @throws IOException
  4. */
  5. public String exportXls() throws IOException{
  6. //第一步:查询所有的分区数据
  7. List<Subarea> list = subareaService.findAll();
  8.  
  9. //第二步:使用POI将数据写到Excel文件中
  10. //在内存中创建一个Excel文件
  11. HSSFWorkbook workbook = new HSSFWorkbook();
  12. //创建一个标签页
  13. HSSFSheet sheet = workbook.createSheet("分区数据");
  14. //创建标题行
  15. HSSFRow headRow = sheet.createRow(0);
  16. headRow.createCell(0).setCellValue("分区编号");
  17. headRow.createCell(1).setCellValue("开始编号");
  18. headRow.createCell(2).setCellValue("结束编号");
  19. headRow.createCell(3).setCellValue("位置信息");
  20. headRow.createCell(4).setCellValue("省市区");
  21.  
  22.     //遍历list集合
  23.      for (Subarea subarea : list) {
  24. HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
  25. dataRow.createCell(0).setCellValue(subarea.getId());
  26. dataRow.createCell(1).setCellValue(subarea.getStartnum());
  27. dataRow.createCell(2).setCellValue(subarea.getEndnum());
  28. dataRow.createCell(3).setCellValue(subarea.getPosition());
  29. dataRow.createCell(4).setCellValue(subarea.getRegion().getName());
  30. }
  31.  
  32. //第三步:使用输出流进行文件下载(一个流、两个头)
  33.  
  34. String filename = "分区数据.xls";
  35. String contentType = ServletActionContext.getServletContext().getMimeType(filename);
  36. ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
  37. ServletActionContext.getResponse().setContentType(contentType);
  38.  
  39. //获取客户端浏览器类型
  40. String agent = ServletActionContext.getRequest().getHeader("User-Agent");
  41. filename = FileUtils.encodeDownloadFilename(filename, agent);
  42. ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+filename);
  43. workbook.write(out);
  44. return NONE;
  45. }

解决下载文件不同浏览器附件名的编码

  1. package cn.itcast.bos.utils;
  2.  
  3. import java.io.IOException;
  4. import java.net.URLEncoder;
  5.  
  6. import sun.misc.BASE64Encoder;
  7.  
  8. public class FileUtils {
  9. /**
  10. * 下载文件时,针对不同浏览器,进行附件名的编码
  11. *
  12. * @param filename
  13. * 下载文件名
  14. * @param agent
  15. * 客户端浏览器
  16. * @return 编码后的下载附件名
  17. * @throws IOException
  18. */
  19. public static String encodeDownloadFilename(String filename, String agent)
  20. throws IOException {
  21. if (agent.contains("Firefox")) { // 火狐浏览器
  22. filename = "=?UTF-8?B?"
  23. + new BASE64Encoder().encode(filename.getBytes("utf-8"))
  24. + "?=";
  25. filename = filename.replaceAll("\r\n", "");
  26. } else { // IE及其他浏览器
  27. filename = URLEncoder.encode(filename, "utf-8");
  28. filename = filename.replace("+"," ");
  29. }
  30. return filename;
  31. }
  32. }

使用POI将数据写到Excel中

  1. @RequestMapping(value="/item/downloadaccount.action")
  2. public String downloadAccount(QueryVo vo,Model model,HttpServletRequest request,
  3. HttpServletResponse response,HttpSession session) throws Exception{
  4.  
  5. Integer userId = CommonUtils.getLoginUserId(session);
  6.  
  7. vo.setUserId(userId); // 设置当前登录用户的id
  8.  
  9. //查询登录用户的所有account信息
  10. List<Account> accountList = itemService.QueryAccountList(vo);
  11.  
  12. //在内存中创建一个Excel文件
  13. HSSFWorkbook workbook = new HSSFWorkbook();
  14.  
  15. //创建一个标签页
  16. HSSFSheet sheet = workbook.createSheet("Sheet1");
  17.  
  18. //创建标题行
  19. HSSFRow headRow = sheet.createRow(0);
  20. headRow.createCell(0).setCellValue("account_id");
  21. headRow.createCell(1).setCellValue("website");
  22. headRow.createCell(2).setCellValue("url");
  23. headRow.createCell(3).setCellValue("account");
  24. headRow.createCell(4).setCellValue("username");
  25. headRow.createCell(5).setCellValue("mail");
  26. headRow.createCell(6).setCellValue("telephone");
  27. headRow.createCell(7).setCellValue("hint");
  28.  
  29. //遍历list集合
  30. for (Account ac : accountList) {
  31. HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
  32. dataRow.createCell(0).setCellValue(ac.getId());
  33. dataRow.createCell(1).setCellValue(ac.getWebsite());
  34. dataRow.createCell(2).setCellValue(ac.getUrl());
  35. dataRow.createCell(3).setCellValue(ac.getAccount());
  36. dataRow.createCell(4).setCellValue(ac.getUsername());
  37. dataRow.createCell(5).setCellValue(ac.getMail());
  38. dataRow.createCell(6).setCellValue(ac.getTelephone());
  39. dataRow.createCell(7).setCellValue(ac.getHint());
  40. }
  41. //使用输出流进行文件下载(一个流、两个头)
  42.  
  43. String filename = "account.xls";
  44. String contentType =request.getServletContext().getMimeType(filename);
  45. ServletOutputStream out = response.getOutputStream();
  46. response.setContentType(contentType);
  47.  
  48. //获取客户端浏览器类型
  49. String agent = request.getHeader("User-Agent");
  50. filename = this.encodeDownloadFilename(filename, agent);
  51. response.setHeader("content-disposition", "attachment;filename="+filename);
  52. workbook.write(out);
  53. return null;
  54. }
  55.  
  56. /**
  57. * 下载文件时,针对不同浏览器,进行附件名的编码
  58. *
  59. * @param filename
  60. * 下载文件名
  61. * @param agent
  62. * 客户端浏览器
  63. * @return 编码后的下载附件名
  64. * @throws IOException
  65. */
  66. private String encodeDownloadFilename(String filename, String agent)
  67. throws IOException {
  68. if (agent.contains("Firefox")) { // 火狐浏览器
  69. filename = "=?UTF-8?B?"
  70. + new BASE64Encoder().encode(filename.getBytes("utf-8"))
  71. + "?=";
  72. filename = filename.replaceAll("\r\n", "");
  73. } else { // IE及其他浏览器
  74. filename = URLEncoder.encode(filename, "utf-8");
  75. filename = filename.replace("+"," ");
  76. }
  77. return filename;
  78. }

apache POI技术的使用的更多相关文章

  1. java的poi技术读取Excel数据到MySQL

    这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...

  2. java的poi技术写Excel的Sheet

    在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...

  3. java的poi技术读,写Excel[2003-2007,2010]

    在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...

  4. java的poi技术读取Excel[2003-2007,2010]

    这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...

  5. Apache POI 一键上传(导入excel文件到数据库)

    import cn.XXXX.bos.utils.PinYin4jUtils; import org.apache.commons.lang3.StringUtils; // HSSF:操作07版本之 ...

  6. java的poi技术读取和导入Excel实例

    本篇文章主要介绍了java的poi技术读取和导入Excel实例,报表输出是Java应用开发中经常涉及的内容,有需要的可以了解一下. 报表输出是Java应用开发中经常涉及的内容,而一般的报表往往缺乏通用 ...

  7. java的poi技术读取Excel数据

    这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...

  8. Java导出数据行写入到Excel表格:基于Apache POI

    Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...

  9. java poi技术读取到数据库

    https://www.cnblogs.com/hongten/p/java_poi_excel.html java的poi技术读取Excel数据到MySQL 这篇blog是介绍java中的poi技术 ...

随机推荐

  1. 导出Excel多个表多个sheet

    protected void Page_Load(object sender, EventArgs e)    {        DataTable dt = new DataTable();     ...

  2. APP 市场需求网址

    http://mi.talkingdata.com/terminals.html?terminalType=4

  3. Python-第三方库requests详解(附requests中文官方教程)

    转自http://blog.csdn.net/cyjs1988/article/details/73294774 Python+requests中文官方教程: http://www.python-re ...

  4. Mac下配置MAMP Pro+PHPStorm

    一.配置MAMP Pro Hosts 下载地址:http://xclient.info/s/mamp-pro.html 在Hosts页签下,如图所示位置选择你工程目录 二.配置PHPStorm 1.点 ...

  5. easyui rowspan

    第一种写法 columns: [ [ { field: 'depName', title: '部门', rowspan: 2, width: '100px', align: 'center' }, { ...

  6. Powershell Deploy Service Fabric Application To Local Cluster

    之前写过一篇用 Powershell 部署 Service Fabric Application 到本地集群的随笔,感觉过程有点复杂,这次将流程简化,只需要将应用程序打包,加上配置文件就可以了.   ...

  7. 在FooterTemplate内显示DropDownList控件

    如果想在Gridview控件FooterTemplate内显示DropDownList控件供用户添加数据时所应用.有两种方法可以实现,一种是在GridView控件的OnRowDataBound事件中写 ...

  8. 网易CentOS yum源

    wget http://mirrors.163.com/.help/CentOS6-Base-163.repo

  9. Shell学习日记

    if语句的使用 if语句的的格式: if [ expression ] expression 和方括号([ ])之间必须有空格,否则会有语法错误. then statments fi 或者: if [ ...

  10. Django / Python 链接MySQL数据库

    https://www.cnblogs.com/wupeiqi/articles/5237704.html python (Django)中使用MySQL 首先python3中没有 MySQLdb 需 ...