当前位置: 移动技术网 > IT编程>开发语言>Java > Apache POI详解

Apache POI详解

2019年12月27日  | 移动技术网IT编程  | 我要评论

一 :简介


  开发中经常会设计到excel的处理,如导出excel,导入excel到数据库中,操作excel目前有两个框架,一个是apache 的poi, 另一个是 java excel

  apache poi 简介是用java编写的免费开源的跨平台的 java api,apache poi提供api给java程式对microsoft office(excel、word、powerpoint、visio等)格式档案读和写的功能。poi为“poor obfuscation implementation”的首字母缩写,意为“可怜的模糊实现”。

  官方主页: http://poi.apache.org/
  api文档: http://poi.apache.org/apidocs/

  java excel是一开放源码项目,通过它java开发人员可以读取excel文件的内容、创建新的excel文件、更新已经存在的excel文件。jxl 由于其小巧 易用的特点, 逐渐已经取代了 poi-excel的地位, 成为了越来越多的java开发人员生成excel文件的首选。

  由于apache poi 在项目中用的比较多,本篇博客只讲解apache poi,不讲jxl

二:apache poi常用的类


  hssf - 提供读写microsoft excel xls格式档案的功能。
  xssf - 提供读写microsoft excel ooxml xlsx格式档案的功能。
  hwpf - 提供读写microsoft word doc97格式档案的功能。
  xwpf - 提供读写microsoft word doc2003格式档案的功能。
  hslf - 提供读写microsoft powerpoint格式档案的功能。
  hdgf - 提供读microsoft visio格式档案的功能。
  hpbf - 提供读microsoft publisher格式档案的功能。
  hsmf - 提供读microsoft outlook格式档案的功能。


  在开发中我们经常使用hssf用来操作excel处理表格数据,对于其它的不经常使用。

  hssf 是horrible spreadsheet format的缩写,通过hssf,你可以用纯java代码来读取、写入、修改excel文件。hssf 为读取操作提供了两类api:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。

 

常用的类和方法


hssfworkbook :工作簿,代表一个excel的整个文档
  hssfworkbook(); // 创建一个新的工作簿
  hssfworkbook(inputstream inputstream); // 创建一个关联输入流的工作簿,可以将一个excel文件封装成工作簿
  hssfsheet createsheet(string sheetname); 创建一个新的sheet
  hssfsheet getsheet(string sheetname); 通过名称获取sheet
  hssfsheet getsheetat(int index); // 通过索引获取sheet,索引从0开始
  hssfcellstyle createcellstyle(); 创建单元格样式
  int getnumberofsheets(); 获取sheet的个数
  setactivesheet(int index); 设置默认选中的工作表
  write();
  write(file newfile);
  write(outputstream stream);
hssfsheet:工作表
  hssfrow createrow(int rownum); 创建新行,需要指定行号,行号从0开始
  hssfrow getrow(int index); 根据索引获取指定的行
  int addmergedregion(cellrangeaddress region); 合并单元格
  cellrangeaddress(int firstrow, int lastrow, int firstcol, int lastcol); 单元格范围, 用于合并单元格,需要指定要合并的首行、最后一行、首列、最后一列。
  autosizecolumn(int column); 自动调整列的宽度来适应内容
  getlastrownum(); 获取最后的行的索引,没有行或者只有一行的时候返回0
  setcolumnwidth(int columnindex, int width); 设置某一列的宽度,width=字符个数 * 256,例如20个字符的宽度就是20 * 256
hssfrow :行
  hssfcell createcell(int column); 创建新的单元格
  hssfcell setcell(shot index);
  hssfcell getcell(shot index);
  setrowstyle(hssfcellstyle style); 设置行样式
  short getlastcellnum(); 获取最后的单元格号,如果单元格有第一个开始算,lastcellnum就是列的个数
  setheightinpoints(float height); 设置行的高度
hssfcell:单元格
  setcellvalue(string value); 设置单元格的值
  setcelltype(); 设置单元格类型,如 字符串、数字、布尔等
  setcellstyle(); 设置单元格样式
  string getstringcellvalue(); 获取单元格中的字符串值
  setcellstyle(hssfcellstyle style); 设置单元格样式,例如字体、加粗、格式化
  setcellformula(string formula); 设置计算公式,计算的结果作为单元格的值,也提供了异常常用的函数,如求和"sum(a1,c1)"、日期函数、字符串相关函数、countif和sumif函数、随机数函数等
hssfcellstyle :单元格样式
  setfont(font font); 为单元格设置字体样式
  setalignment(horizontalalignment align); // 设置水平对齐方式
  setverticalalignment(verticalalignment align); // 设置垂直对齐方式
  setfillpattern(fillpatterntype fp);
  setfillforegroundcolor(short bg); 设置前景色
  setfillbackgroundcolor(short bg); 设置背景颜色
hssffont:字体
  setcolor(short color); // 设置字体颜色
  setbold(boolean bold); // 设置是否粗体
  setitalic(boolean italic); 设置倾斜
  setunderline(byte underline); 设置下划线
hssfname:名称
hssfdataformat :日期格式化
hssfheader : sheet的头部
hssffooter :sheet的尾部
hssfdateutil :日期工具
hssfprintsetup :打印设置
hssferrorconstants:错误信息表


excel中的工作簿、工作表、行、单元格中的关系:

一个excel文件对应于一个workbook(hssfworkbook),
一个workbook可以有多个sheet(hssfsheet)组成,
一个sheet是由多个row(hssfrow)组成,
一个row是由多个cell(hssfcell)组成


三:基础示例


首先引入apache poi的依赖

1 <dependency> 
2 <groupid>org.apache.poi</groupid> 
3 <artifactid>poi</artifactid> 
4 <version>3.8</version> 
5 </dependency>

 


示例一:在桌面上生成一个excel文件

 

 1 public static void createexcel() throws ioexception{
 2 // 获取桌面路径
 3 filesystemview fsv = filesystemview.getfilesystemview();
 4 string desktop = fsv.gethomedirectory().getpath();
 5 string filepath = desktop + "/template.xls";
 6 
 7 file file = new file(filepath);
 8 outputstream outputstream = new fileoutputstream(file);
 9 hssfworkbook workbook = new hssfworkbook();
10 hssfsheet sheet = workbook.createsheet("sheet1");
11 hssfrow row = sheet.createrow(0);
12 row.createcell(0).setcellvalue("id");
13 row.createcell(1).setcellvalue("订单号");
14 row.createcell(2).setcellvalue("下单时间");
15 row.createcell(3).setcellvalue("个数");
16 row.createcell(4).setcellvalue("单价");
17 row.createcell(5).setcellvalue("订单金额");
18 row.setheightinpoints(30); // 设置行的高度
19 
20 hssfrow row1 = sheet.createrow(1);
21 row1.createcell(0).setcellvalue("1");
22 row1.createcell(1).setcellvalue("no00001");
23 
24 // 日期格式化
25 hssfcellstyle cellstyle2 = workbook.createcellstyle();
26 hssfcreationhelper creationhelper = workbook.getcreationhelper();
27 cellstyle2.setdataformat(creationhelper.createdataformat().getformat("yyyy-mm-dd hh:mm:ss"));
28 sheet.setcolumnwidth(2, 20 * 256); // 设置列的宽度
29 
30 hssfcell cell2 = row1.createcell(2);
31 cell2.setcellstyle(cellstyle2);
32 cell2.setcellvalue(new date());
33 
34 row1.createcell(3).setcellvalue(2);
35 
36 
37 // 保留两位小数
38 hssfcellstyle cellstyle3 = workbook.createcellstyle();
39 cellstyle3.setdataformat(hssfdataformat.getbuiltinformat("0.00"));
40 hssfcell cell4 = row1.createcell(4);
41 cell4.setcellstyle(cellstyle3);
42 cell4.setcellvalue(29.5);
43 
44 
45 // 货币格式化
46 hssfcellstyle cellstyle4 = workbook.createcellstyle();
47 hssffont font = workbook.createfont();
48 font.setfontname("华文行楷");
49 font.setfontheightinpoints((short)15);
50 font.setcolor(hssfcolor.red.index);
51 cellstyle4.setfont(font);
52 
53 hssfcell cell5 = row1.createcell(5);
54 cell5.setcellformula("d2*e2"); // 设置计算公式
55 
56 // 获取计算公式的值
57 hssfformulaevaluator e = new hssfformulaevaluator(workbook);
58 cell5 = e.evaluateincell(cell5);
59 system.out.println(cell5.getnumericcellvalue());
60 
61 
62 workbook.setactivesheet(0);
63 workbook.write(outputstream);
64 outputstream.close();
65 }

 

 

示例2:读取excel,解析数据

 1 public static void readexcel() throws ioexception{
 2 filesystemview fsv = filesystemview.getfilesystemview();
 3 string desktop = fsv.gethomedirectory().getpath();
 4 string filepath = desktop + "/template.xls";
 5 
 6 fileinputstream fileinputstream = new fileinputstream(filepath);
 7 bufferedinputstream bufferedinputstream = new bufferedinputstream(fileinputstream);
 8 poifsfilesystem filesystem = new poifsfilesystem(bufferedinputstream);
 9 hssfworkbook workbook = new hssfworkbook(filesystem);
10 hssfsheet sheet = workbook.getsheet("sheet1");
11 
12 int lastrowindex = sheet.getlastrownum();
13 system.out.println(lastrowindex);
14 for (int i = 0; i <= lastrowindex; i++) {
15 hssfrow row = sheet.getrow(i);
16 if (row == null) { break; }
17 
18 short lastcellnum = row.getlastcellnum();
19 for (int j = 0; j < lastcellnum; j++) {
20 string cellvalue = row.getcell(j).getstringcellvalue();
21 system.out.println(cellvalue);
22 }
23 }
24 
25 bufferedinputstream.close();
26 }

 

四:java web 中导出和导入excel


1、导出示例

 1 @suppresswarnings("resource")
 2 @requestmapping("/export") 
 3 public void exportexcel(httpservletresponse response, httpsession session, string name) throws exception { 
 4 
 5 string[] tableheaders = {"id", "姓名", "年龄"}; 
 6 
 7 hssfworkbook workbook = new hssfworkbook();
 8 hssfsheet sheet = workbook.createsheet("sheet1");
 9 hssfcellstyle cellstyle = workbook.createcellstyle(); 
10 cellstyle.setalignment(horizontalalignment.center); 
11 cellstyle.setverticalalignment(verticalalignment.center);
12 
13 font font = workbook.createfont(); 
14 font.setcolor(hssfcolor.red.index); 
15 font.setbold(true);
16 cellstyle.setfont(font);
17 
18 // 将第一行的三个单元格给合并
19 sheet.addmergedregion(new cellrangeaddress(0, 0, 0, 2));
20 hssfrow row = sheet.createrow(0);
21 hssfcell begincell = row.createcell(0);
22 begincell.setcellvalue("通讯录");    
23 begincell.setcellstyle(cellstyle);
24 
25 row = sheet.createrow(1);
26 // 创建表头
27 for (int i = 0; i < tableheaders.length; i++) {
28 hssfcell cell = row.createcell(i);
29 cell.setcellvalue(tableheaders[i]);
30 cell.setcellstyle(cellstyle); 
31 }
32 
33 list<user> users = new arraylist<>();
34 users.add(new user(1l, "张三", 20));
35 users.add(new user(2l, "李四", 21));
36 users.add(new user(3l, "王五", 22));
37 
38 for (int i = 0; i < users.size(); i++) {
39 row = sheet.createrow(i + 2);
40 
41 user user = users.get(i);
42 row.createcell(0).setcellvalue(user.getid()); 
43 row.createcell(1).setcellvalue(user.getname()); 
44 row.createcell(2).setcellvalue(user.getage()); 
45 }
46 
47 outputstream outputstream = response.getoutputstream(); 
48 response.reset(); 
49 response.setcontenttype("application/vnd.ms-excel"); 
50 response.setheader("content-disposition", "attachment;filename=template.xls");
51 
52 workbook.write(outputstream);
53 outputstream.flush(); 
54 outputstream.close();
55 }

 

2、导入示例


  1、使用springmvc上传文件,需要用到commons-fileupload

  

1 <dependency>
2 <groupid>commons-fileupload</groupid>
3 <artifactid>commons-fileupload</artifactid>
4 <version>1.3</version>
5 </dependency>

 

  2、需要在spring的配置文件中配置一下multipartresolver

1 <bean name="multipartresolver" 
2 class="org.springframework.web.multipart.commons.commonsmultipartresolver"> 
3 <property name="defaultencoding" value="utf-8" />
4 </bean>

 

  3、index.jsp

1 <a href="/spring-mybatis-druid/user/export">导出</a> <br/>
2 
3 <form action="/spring-mybatis-druid/user/import" enctype="multipart/form-data" method="post">
4     <input type="file" name="file"/> 
5     <input type="submit" value="导入excel">
6 </form>

 

  4、解析上传的.xls文件

 

 1 @suppresswarnings("resource")
 2 @requestmapping("/import")
 3 public void importexcel(@requestparam("file") multipartfile file) throws exception{
 4 inputstream inputstream = file.getinputstream();
 5 bufferedinputstream bufferedinputstream = new bufferedinputstream(inputstream);
 6 poifsfilesystem filesystem = new poifsfilesystem(bufferedinputstream);
 7 hssfworkbook workbook = new hssfworkbook(filesystem);
 8 //hssfworkbook workbook = new hssfworkbook(file.getinputstream());
 9 hssfsheet sheet = workbook.getsheetat(0);
10 
11 int lastrownum = sheet.getlastrownum();
12 for (int i = 2; i <= lastrownum; i++) {
13 hssfrow row = sheet.getrow(i);
14 int id = (int) row.getcell(0).getnumericcellvalue();
15 string name = row.getcell(1).getstringcellvalue();
16 int age = (int) row.getcell(2).getnumericcellvalue();
17 
18 system.out.println(id + "-" + name + "-" + age);
19 }
20 }

 

项目示例代码下载地址:

http://download.csdn.net/detail/vbirdbest/9861536

 

————————————————
版权声明:本文为csdn博主「vbirdbest」的原创文章,遵循 cc 4.0 by-sa 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/vbirdbest/article/details/72870714

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网