POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】
实际开发过程中通常用到的就是从数据库导出EXCEL表格了,JXL可以这样做,其实POI也可以(关于JXL与POI的异同可访问我之前总结的文章),之前写过POI对七种文档(当然也包括EXCEL)的内容读取操作的文章,这次要写的就非常重要了,就是开发中经常会用到的POI读取数据库导出EXCEL的操作,所谓导出EXCEL也就是生成带数据内容的新的EXCEL文件
目前的POI版本是3.7
下载地址:http://poi.apache.org/download.html#POI-3.7
必须包只有一个:poi-3.7-20101029.jar
整理思路:1)数据库中的字段对应EXCEL的最顶层一行各个CELL名称[也就是上面图片中序号版本...的]
2)将每个数据一次插入到对应名称CELL的对应记录位置
3)为了方便操作,顶层的cell各个名称可以抽取出来成为一个单独类
具体代码
第一部分:单独的EXCEL表头类
public class Cachetable {
- // Fields
- private int recnum;
- private String devIp;
- private String srcaddr;
- private String dstaddr;
- private String nexthop;
- private String input;
- private String output;
- private String dpkts;
- private String doctets;
- private String sstart;
- private String dstport;
- private String prot;
- private String tos;
- private String srcas;
- private String dstas;
- private String pduversion;
- /** default constructor */
- public Cachetable() {
- }
- /** full constructor */
- public Cachetable(int recnum, String devIp, String srcaddr, String dstaddr, String nexthop, String input, String output, String dpkts, String doctets, String sstart, String dstport, String prot, String tos, String srcas, String dstas,String pduversion) {
- this.recnum = recnum;
- this.devIp = devIp;
- this.srcaddr = srcaddr;
- this.dstaddr = dstaddr;
- this.nexthop = nexthop;
- this.input = input;
- this.output = output;
- this.dpkts = dpkts;
- this.doctets = doctets;
- this.sstart = sstart;
- this.dstport = dstport;
- this.prot = prot;
- this.tos = tos;
- this.srcas = srcas;
- this.dstas = dstas;
- this.pduversion = pduversion;
- }
- public int getRecnum() {
- return this.recnum;
- }
- public void setRecnum(int recnum) {
- this.recnum= recnum;
- }
- public String getDevIp() {
- return this.devIp;
- }
- public void setDevIp(String devIp) {
- this.devIp = devIp;
- }
- public String getSrcaddr() {
- return this.srcaddr;
- }
- public void setSrcaddr(String srcaddr) {
- this.srcaddr = srcaddr;
- }
- public String getDstaddr() {
- return this.dstaddr;
- }
- public void setDstaddr(String dstaddr) {
- this.dstaddr = dstaddr;
- }
- public String getNexthop() {
- return this.nexthop;
- }
- public void setNexthop(String nexthop) {
- this.nexthop = nexthop;
- }
- public String getInput() {
- return this.input;
- }
- public void setInput(String input) {
- this.input = input;
- }
- public String getOutput() {
- return this.output;
- }
- public void setOutput(String output) {
- this.output = output;
- }
- public String getDpkts() {
- return this.dpkts;
- }
- public void setDpkts(String dpkts) {
- this.dpkts = dpkts;
- }
- public String getDoctets() {
- return this.doctets;
- }
- public void setDoctets(String doctets) {
- this.doctets = doctets;
- }
- public String getSstart() {
- return this.sstart;
- }
- public void setSstart(String sstart) {
- this.sstart = sstart;
- }
- public String getDstport() {
- return this.dstport;
- }
- public void setDstport(String dstport) {
- this.dstport = dstport;
- }
- public String getProt() {
- return this.prot;
- }
- public void setProt(String prot) {
- this.prot = prot;
- }
- public String getTos() {
- return this.tos;
- }
- public void setTos(String tos) {
- this.tos = tos;
- }
- public String getSrcas() {
- return this.srcas;
- }
- public void setSrcas(String srcas) {
- this.srcas = srcas;
- }
- public String getDstas() {
- return this.dstas;
- }
- public void setDstas(String dstas) {
- this.dstas = dstas;
- }
- public String getPduversion() {
- return this.pduversion;
- }
- public void setPduversion(String pduversion) {
- this.pduversion = pduversion;
- }
第二部分:具体的POI操作生成EXCEL类
【我这里只是个示例,没连数据库,直接运行即可,如果想连,稍微变动一点即可】
- package com.zkyy.flow.excel;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.swing.JOptionPane;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFCellStyle;
- import org.apache.poi.hssf.usermodel.HSSFDataFormat;
- import org.apache.poi.hssf.usermodel.HSSFFooter;
- import org.apache.poi.hssf.usermodel.HSSFHeader;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import com.kk.flow.webapp.util.Cachetable;
- public class ExcelOut {
- //表头
- public static final String[] tableHeader = {"序号","版本","接收时刻","设备","入接口","出接口",
- "源IP","目的IP","下一跳","协议","端口","对端端口","TOS","源AS","目的AS","TCP_FLAG","pad1","pad2"};
- //创建工作本 TOS
- public static HSSFWorkbook demoWorkBook = new HSSFWorkbook();
- //创建表
- public static HSSFSheet demoSheet = demoWorkBook.createSheet("The World's 500 Enterprises");
- //表头的单元格个数目
- public static final short cellNumber = (short)tableHeader.length;
- //数据库表的列数
- public static final int columNumber = 1;
- /**
- * 创建表头
- * @return
- */
- public static void createTableHeader()
- {
- HSSFHeader header = demoSheet.getHeader();
- header.setCenter("世界五百强企业名次表");
- HSSFRow headerRow = demoSheet.createRow((short) 0);
- for(int i = 0;i < cellNumber;i++)
- {
- HSSFCell headerCell = headerRow.createCell((short) i);
- headerCell.setCellType(HSSFCell.CELL_TYPE_STRING);
- headerCell.setCellValue(tableHeader[i]);
- }
- }
- /**
- * 创建行
- * @param cells
- * @param rowIndex
- */
- public static void createTableRow(List<String> cells,short rowIndex)
- {
- //创建第rowIndex行
- HSSFRow row = demoSheet.createRow((short) rowIndex);
- for(int i = 0;i < cells.size();i++)
- {
- //创建第i个单元格
- HSSFCell cell = row.createCell(i);
- if(cell.getCellType()!=1){
- cell.setCellType(HSSFCell.CELL_TYPE_STRING);
- }
- //新增的四句话,设置CELL格式为文本格式
- HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle();
- HSSFDataFormat format = demoWorkBook.createDataFormat();
- cellStyle2.setDataFormat(format.getFormat("@"));
- cell.setCellStyle(cellStyle2);
- cell.setCellValue(cells.get(i));
- cell.setCellType(HSSFCell.CELL_TYPE_STRING);
- }
- }
- /**
- * USE:用于获取Cachetable的数据。。。假数据。到时候:你连接数据库的到List<Cachetable>的数据就行了。 共生成
- * 100条数据.相当于100行
- *
- * @return
- */
- public List<Cachetable> getDate() {
- List<Cachetable> cacheList = new ArrayList<Cachetable>();
- for (int j = 0; j < 300; j++) {
- Cachetable tb = new Cachetable();
- tb.setRecnum(j + 1);
- tb.setDevIp("JavaCrazyer");
- tb.setSrcaddr("北京");
- tb.setDstaddr("xxx");
- tb.setNexthop("yy");
- tb.setInput("123");
- tb.setOutput("127.0.0.1");
- tb.setDpkts("what are you doing?");
- tb.setDoctets("who are you?");
- tb.setSstart("Oh sure!");
- tb.setProt("One");
- tb.setTos("two");
- tb.setSrcas("three");
- tb.setDstas("four");
- tb.setPduversion("不知道");
- cacheList.add(tb);
- }
- return cacheList;
- }
- /**
- * 创建整个Excel表
- * @throws SQLException
- *
- */
- public void createExcelSheet() throws SQLException{
- createTableHeader();
- int rowIndex=1;
- List<Cachetable> list=getDate();
- for(int j=0;j<list.size();j++){
- List<String> listRead=new ArrayList<String>();
- for(int i=1;i<=columNumber;i++){
- listRead.add(list.get(i).getDevIp());
- listRead.add(list.get(i).getSrcaddr());
- listRead.add(list.get(i).getDstaddr());
- listRead.add(list.get(i).getNexthop());
- listRead.add(list.get(i).getInput());
- listRead.add(list.get(i).getOutput());
- listRead.add(list.get(i).getDpkts());
- listRead.add(list.get(i).getDoctets());
- listRead.add(list.get(i).getSstart());
- listRead.add(list.get(i).getProt());
- listRead.add(list.get(i).getTos());
- listRead.add(list.get(i).getSrcas());
- listRead.add(list.get(i).getDstas());
- listRead.add(list.get(i).getPduversion());
- listRead.add(rowIndex+"");
- }
- createTableRow(listRead,(short)rowIndex);
- rowIndex++;
- }
- }
- /**
- * 导出表格
- * @param sheet
- * @param os
- * @throws IOException
- */
- public void exportExcel(HSSFSheet sheet,OutputStream os) throws IOException
- {
- sheet.setGridsPrinted(true);
- HSSFFooter footer = sheet.getFooter();
- footer.setRight("Page " + HSSFFooter.page() + " of " +
- HSSFFooter.numPages());
- demoWorkBook.write(os);
- }
- public static void main(String[] args) {
- String fileName = "f:\\世界五百强企业名次表.xls";
- FileOutputStream fos = null;
- try {
- ExcelOut pd = new ExcelOut();
- pd.createExcelSheet();
- fos = new FileOutputStream(fileName);
- pd.exportExcel(demoSheet,fos);
- JOptionPane.showMessageDialog(null, "表格已成功导出到 : "+fileName);
- } catch (Exception e) {
- JOptionPane.showMessageDialog(null, "表格导出出错,错误信息 :"+e+"\n错误原因可能是表格已经打开。");
- e.printStackTrace();
- } finally {
- try {
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
说明:
1)有关数据库连接,如果操作到数据库的话,在遍历数据库时用getDate这个方法遍历就可以啦,那么插入的数据就不是定值了,而是数据库中的值哦,具体操作数据库的步骤,我不用说,你懂得
2)有关涉及更改EXCEL的CELL格式为字符串,如图一般情况下大家导出的EXCEL表格CELL格式通常是常规的
这个问题,估计已经不止一两个朋友在网上问过,我至今没有看到一个满意的答案,通常大家都是想到既然是设置CELL格式肯定是通过cell.setCellType(HSSFCell.CELL_TYPE_STRING)然后插入数据再导出,诚然这种想法是对的,实际上不能起到任何作用,因为这个方法就是EXCEL默认的格式,写不写都一样(好多同学都不知道吧),再写出我的解决方案之前请大家参考下一段文字
第一段:Excel的单元格格式
图中的数据有数值、货币、时间、日期、文本等格式。这些数据格式在POI中的HSSFDataFormat类里都有相应的定义。
HSSFDataFormat是HSSF子项目里面定义的一个类。类HSSFDataFormat允许用户新建数据格式类型。HSSFDataFormat类包含静态方法static java.lang.String getBuiltinFormat(short index),它可以根据编号返回内置数据类型。另外static short getBuiltinFormat(java.lang.String format)方法则可以根据数据类型返回其编号,static java.util.List getBuiltinFormats()可以返回整个内置的数据格式列表。
在HSSFDataFormat里一共定义了49种内置的数据格式,如下面所示。
HSSFDataFormat的数据格式
内置数据类型
编号
"General"
0
"0"
1
"0.00"
2
"#,##0"
3
"#,##0.00"
4
"($#,##0_);($#,##0)"
5
"($#,##0_);[Red]($#,##0)"
6
"($#,##0.00);($#,##0.00)"
7
"($#,##0.00_);[Red]($#,##0.00)"
8
"0%"
9
"0.00%"
0xa
"0.00E+00"
0xb
"# ?/?"
0xc
"# ??/??"
0xd
"m/d/yy"
0xe
"d-mmm-yy"
0xf
"d-mmm"
0x10
"mmm-yy"
0x11
"h:mm AM/PM"
0x12
"h:mm:ss AM/PM"
0x13
"h:mm"
0x14
"h:mm:ss"
0x15
"m/d/yy h:mm"
0x16
保留为过国际化用
0x17 - 0x24
"(#,##0_);(#,##0)"
0x25
"(#,##0_);[Red](#,##0)"
0x26
"(#,##0.00_);(#,##0.00)"
0x27
"(#,##0.00_);[Red](#,##0.00)"
0x28
"_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"
0x29
"_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"
0x2a
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2b
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2c
"mm:ss"
0x2d
"[h]:mm:ss"
0x2e
"mm:ss.0"
0x2f
"##0.0E+0"
0x30
"@" - This is text format
0x31
在上面表中,字符串类型所对应的是数据格式为"@"(最后一行),也就是HSSFDataFormat中定义的值为0x31(49)的那行。Date类型的值的范围是0xe-0x11,本例子中的Date格式为""m/d/yy"",在HSSFDataFormat定义的值为0xe(14)。
第二段:POI中Excel文件Cell的类型
在读取每一个Cell的值的时候,通过getCellType方法获得当前Cell的类型,在Excel中Cell有6种类型,如下面所示。
Cell的类型
CellType
说明
CELL_TYPE_BLANK
空值
CELL_TYPE_BOOLEAN
布尔型
CELL_TYPE_ERROR
错误
CELL_TYPE_FORMULA
公式型
CELL_TYPE_STRING
字符串型
CELL_TYPE_NUMERIC
数值型
一般都采用CELL_TYPE_STRING和CELL_TYPE_NUMERIC类型,因为在Excel文件中只有字符串和数字。如果Cell的Type为CELL_TYPE_NUMERIC时,还需要进一步判断该Cell的数据格式,因为它有可能是Date类型,在Excel中的Date类型也是以Double类型的数字存储的。Excel中的Date表示当前时间与1900年1月1日相隔的天数,所以需要调用HSSFDateUtil的isCellDateFormatted方法,判断该Cell的数据格式是否是Excel Date类型。如果是,则调用getDateCellValue方法,返回一个Java类型的Date。
好了读完上面两段文字我想大家关于CELL类型和格式应该清楚了,更应该清楚的是到底怎么才能将‘设置单元格格式’改成文本然后再导出
解决方案:就是上面代码中的ExcelOut类里面createTableRow方法中的一段代码
HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle();
HSSFDataFormat format = demoWorkBook.createDataFormat();
cellStyle2.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle2);
看最终导出效果图吧,点击任何一个CELL右键设置单元格格式
3) JOptionPane.showMessageDialog(null, "表格已成功导出到 : "+fileName);这句话有点意思
看到没这就是javax.swing.JOptionPane类的有关消息输出的好处,很方便使用
POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】的更多相关文章
- POI对Excel单元格进行颜色设置
POI对Excel单元格进行颜色设置 学习了:http://www.myexception.cn/program/1932587.html HSSFWorkbook workbook = new HS ...
- 学会简单使用poi进行excel有关操作
直接上代码: 官网上的抄的api例子: package com.test; import java.io.File; import java.io.FileInputStream; import ja ...
- POI对Excel的操作
1. 先导包 commons-io-2.6.jar包,用于对文件的操作. 下载地址:http://commons.apache.org/proper/commons-io/download_io.cg ...
- jspsmart(保存文件)+poi(读取excel文件)操作excel文件
写在前面: 项目环境:jdk1.4+weblogic 需求:能上传excel2003+2007 由于项目不仅需要上传excel2003,还要上传excel2007,故我们抛弃了jxl(只能上传exce ...
- poi对EXCEL的操作(一)
(原创自己这段时间对poi的研究心得) 一.基础的对象 1.wookbook工作簿 创建工作簿 wookbook XSSFWorkbook类的构造方法 XSSFWorkbook ...
- java poi导出Excel合并单元格并设置边框
import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; i ...
- poi对excel的操作(二)
二.进阶的对象 1.CellType 枚举类 单元格类型 CellType.STRING---文本型 等 如何是指单元格类型:cell.setCellType(CellType.STRING) 2.C ...
- 使用POI对excel进行操作生成二维数组
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...
- excel日期格式转换为文本格式
今天测试读取excel并修改数据库数据的时候遇到几个小问题. 1.空指针,读写io异常蛮多的,获取不到的数据就是null 2.读取文件位置,开始找不到文件 3.读取日期格式结果是一个数值,因此需要转化 ...
随机推荐
- java知识点积累(二)
4.条件运算符(三元运算符): String type = score<60?"不及格":"及格"; int i = (string=="hel ...
- 【转】C# 使用正则表达式去掉字符串中的数字,或者去掉字符串中的非数字
源地址:http://www.cnblogs.com/94cool/p/4332957.html
- 洛谷P1054 等价表达式
P1054 等价表达式 题目描述 明明进了中学之后,学到了代数表达式.有一天,他碰到一个很麻烦的选择题.这个题目的题干中首先给出了一个代数表达式,然后列出了若干选项,每个选项也是一个代数表达式,题目的 ...
- JDK动态代理和cglib代理
写一个简单的测试用例,Pig实现了Shout接口 public class MyInvocation implements InvocationHandler { Object k; public M ...
- Filter&Listener
Filter&Listener 内容待补充... ...
- 使用Collectd + InfluxDB + Grafana进行JMX监控
我们已经看到使用Collectd监控CPU /内存利用率(本文).但它没有提供所有信息来确定性能问题的瓶颈.在本文中,我们将使用Collectd Java插件来使用其JMX技术来监视和管理Java虚拟 ...
- 关于after和before
你可曾'百度一下'? 在以前的很多时候,当我断网了,或者网络出了莫名其妙的问题时,我总是第一个输入它的网址.它不仅仅是一个搜索引擎.它还是我检验网络的唯一标准(手动滑稽). CSS中的after和be ...
- JS事件冒泡机制和兼容性添加事件
本篇文章主要来讲讲 事件的冒泡机制 和 添加事件的几种方法. 一. JS的时间传递顺序: 捕获阶段 -> 目标阶段 -> 冒泡阶段 捕获阶段是指从父层往子层找.比如 <body> ...
- linux shell 脚本 历史文件清理脚本,按天,按月,清理前N天的历史文件,删除指定大小历史文件,历史文件归档清理
不知道大家那有没有要清理的这个事情.需要清理目录历史文件.可能后续也会有很多其他地方需要清理历史文件,可能会用到. 我这两天空闲写了个脚本,清理比较方便,有要进行清理的大量历史文件的话可以用. 脚本用 ...
- linux之sed的用法
sed是一个很好的文件处理工具,本身是一个管道命令,主要是以行为单位进行处理,可以将数据行进行替换.删除.新增.选取等特定工作,下面先了解一下sed的用法sed命令行格式为: sed ...