`

POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】

 
阅读更多

POI对EXCEL的操作【重点:如何设置CELL格式为文本格式】
博客分类: 各类文件操作/IO流

ExcelApacheSwingOSJ#.


实际开发过程中通常用到的就是从数据库导出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 {



Java代码 
1.// Fields 
2.private int recnum; 
3.private String devIp; 
4.private String srcaddr; 
5.private String dstaddr; 
6.private String nexthop; 
7.private String input; 
8.private String output; 
9.private String dpkts; 
10.private String doctets; 
11.private String sstart; 
12. 
13.private String dstport; 
14.private String prot; 
15.private String tos; 
16.private String srcas; 
17.private String dstas; 
18.private String pduversion; 
19. 
20. 
21./** default constructor */ 
22.public Cachetable() { 
23.} 
24. 
25. 
26./** full constructor */ 
27.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) { 
28.    this.recnum = recnum; 
29.    this.devIp = devIp; 
30.    this.srcaddr = srcaddr; 
31.    this.dstaddr = dstaddr; 
32.    this.nexthop = nexthop; 
33.    this.input = input; 
34.    this.output = output; 
35.    this.dpkts = dpkts; 
36.    this.doctets = doctets; 
37.    this.sstart = sstart; 
38.    this.dstport = dstport; 
39.    this.prot = prot; 
40.    this.tos = tos; 
41.    this.srcas = srcas; 
42.    this.dstas = dstas; 
43.    this.pduversion = pduversion; 
44. 
45.} 
46. 
47. 
48.public int getRecnum() { 
49.    return this.recnum; 
50.} 
51. 
52.public void setRecnum(int recnum) { 
53.    this.recnum= recnum; 
54.} 
55. 
56.public String getDevIp() { 
57.    return this.devIp; 
58.} 
59. 
60.public void setDevIp(String devIp) { 
61.    this.devIp = devIp; 
62.} 
63. 
64. 
65.public String getSrcaddr() { 
66.    return this.srcaddr; 
67.} 
68. 
69.public void setSrcaddr(String srcaddr) { 
70.    this.srcaddr = srcaddr; 
71.} 
72. 
73. 
74.public String getDstaddr() { 
75.    return this.dstaddr; 
76.} 
77. 
78.public void setDstaddr(String dstaddr) { 
79.    this.dstaddr = dstaddr; 
80.} 
81. 
82. 
83.public String getNexthop() { 
84.    return this.nexthop; 
85.} 
86. 
87.public void setNexthop(String nexthop) { 
88.    this.nexthop = nexthop; 
89.} 
90. 
91. 
92.public String getInput() { 
93.    return this.input; 
94.} 
95. 
96.public void setInput(String input) { 
97.    this.input = input; 
98.} 
99. 
100. 
101.public String getOutput() { 
102.    return this.output; 
103.} 
104. 
105.public void setOutput(String output) { 
106.    this.output = output; 
107.} 
108. 
109.public String getDpkts() { 
110.    return this.dpkts; 
111.} 
112. 
113.public void setDpkts(String dpkts) { 
114.    this.dpkts = dpkts; 
115.} 
116. 
117. 
118.public String getDoctets() { 
119.    return this.doctets; 
120.} 
121. 
122.public void setDoctets(String doctets) { 
123.    this.doctets = doctets; 
124.} 
125. 
126. 
127.public String getSstart() { 
128.    return this.sstart; 
129.} 
130. 
131.public void setSstart(String sstart) { 
132.    this.sstart = sstart; 
133.} 
134. 
135.public String getDstport() { 
136.    return this.dstport; 
137.} 
138. 
139.public void setDstport(String dstport) { 
140.    this.dstport = dstport; 
141.} 
142. 
143.public String getProt() { 
144.    return this.prot; 
145.} 
146. 
147.public void setProt(String prot) { 
148.    this.prot = prot; 
149.} 
150. 
151. 
152.public String getTos() { 
153.    return this.tos; 
154.} 
155. 
156.public void setTos(String tos) { 
157.    this.tos = tos; 
158.} 
159. 
160.public String getSrcas() { 
161.    return this.srcas; 
162.} 
163. 
164.public void setSrcas(String srcas) { 
165.    this.srcas = srcas; 
166.} 
167. 
168. 
169.public String getDstas() { 
170.    return this.dstas; 
171.} 
172. 
173.public void setDstas(String dstas) { 
174.    this.dstas = dstas; 
175.} 
176. 
177.public String getPduversion() { 
178.    return this.pduversion; 
179.} 
180. 
181.public void setPduversion(String pduversion) { 
182.    this.pduversion = pduversion; 
183.} 



第二部分:具体的POI操作生成EXCEL类

【我这里只是个示例,没连数据库,直接运行即可,如果想连,稍微变动一点即可】





Java代码 
1.package com.zkyy.flow.excel; 
2. 
3.import java.io.FileOutputStream; 
4.import java.io.IOException; 
5.import java.io.OutputStream; 
6.import java.sql.SQLException; 
7.import java.util.ArrayList; 
8.import java.util.List; 
9. 
10.import javax.swing.JOptionPane; 
11. 
12.import org.apache.poi.hssf.usermodel.HSSFCell; 
13.import org.apache.poi.hssf.usermodel.HSSFCellStyle; 
14.import org.apache.poi.hssf.usermodel.HSSFDataFormat; 
15.import org.apache.poi.hssf.usermodel.HSSFFooter; 
16.import org.apache.poi.hssf.usermodel.HSSFHeader; 
17.import org.apache.poi.hssf.usermodel.HSSFRow; 
18.import org.apache.poi.hssf.usermodel.HSSFSheet; 
19.import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
20. 
21.import com.kk.flow.webapp.util.Cachetable; 
22.   
23.public class ExcelOut {    
24.   
25.    //表头    
26.    public static final String[] tableHeader = {"序号","版本","接收时刻","设备","入接口","出接口",    
27.        "源IP","目的IP","下一跳","协议","端口","对端端口","TOS","源AS","目的AS","TCP_FLAG","pad1","pad2"};    
28.    //创建工作本   TOS 
29.    public static HSSFWorkbook demoWorkBook = new HSSFWorkbook();    
30.    //创建表    
31.    public static HSSFSheet demoSheet = demoWorkBook.createSheet("The World's 500 Enterprises");    
32.    //表头的单元格个数目    
33.    public static final short cellNumber = (short)tableHeader.length;    
34.    //数据库表的列数    
35.    public static final int columNumber = 1;    
36.    /**  
37.     * 创建表头  
38.     * @return  
39.     */   
40.    public static void createTableHeader()    
41.    {    
42.        HSSFHeader header = demoSheet.getHeader();    
43.        header.setCenter("世界五百强企业名次表");    
44.        HSSFRow headerRow = demoSheet.createRow((short) 0);    
45.        for(int i = 0;i < cellNumber;i++)    
46.        {    
47.            HSSFCell headerCell = headerRow.createCell((short) i);   
48.            headerCell.setCellType(HSSFCell.CELL_TYPE_STRING); 
49.            headerCell.setCellValue(tableHeader[i]);    
50.        }    
51.    }    
52.    /**  
53.     * 创建行  
54.     * @param cells  
55.     * @param rowIndex  
56.     */   
57.    public static void createTableRow(List<String> cells,short rowIndex)    
58.    {    
59.        //创建第rowIndex行    
60.        HSSFRow row = demoSheet.createRow((short) rowIndex);    
61.        for(int i = 0;i < cells.size();i++)    
62.        {    
63.            //创建第i个单元格    
64.            HSSFCell cell = row.createCell(i);  
65.            if(cell.getCellType()!=1){ 
66.                cell.setCellType(HSSFCell.CELL_TYPE_STRING);   
67.            } 
68.             
69.            //新增的四句话,设置CELL格式为文本格式 
70.            HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle(); 
71.            HSSFDataFormat format = demoWorkBook.createDataFormat(); 
72.            cellStyle2.setDataFormat(format.getFormat("@")); 
73.            cell.setCellStyle(cellStyle2); 
74.         
75.            cell.setCellValue(cells.get(i));  
76.            cell.setCellType(HSSFCell.CELL_TYPE_STRING); 
77.        }   
78.    }    
79.     
80.    /**
81.     * USE:用于获取Cachetable的数据。。。假数据。到时候:你连接数据库的到List<Cachetable>的数据就行了。 共生成
82.     * 100条数据.相当于100行
83.     * 
84.     * @return
85.     */ 
86.    public List<Cachetable> getDate() { 
87.        List<Cachetable> cacheList = new ArrayList<Cachetable>(); 
88.        for (int j = 0; j < 300; j++) { 
89.            Cachetable tb = new Cachetable(); 
90.            tb.setRecnum(j + 1); 
91.            tb.setDevIp("JavaCrazyer"); 
92.            tb.setSrcaddr("北京"); 
93.            tb.setDstaddr("xxx"); 
94.            tb.setNexthop("yy"); 
95.            tb.setInput("123"); 
96.            tb.setOutput("127.0.0.1"); 
97.            tb.setDpkts("what are you doing?"); 
98.            tb.setDoctets("who are you?"); 
99.            tb.setSstart("Oh  sure!"); 
100.            tb.setProt("One"); 
101.            tb.setTos("two"); 
102.            tb.setSrcas("three"); 
103.            tb.setDstas("four"); 
104.            tb.setPduversion("不知道"); 
105.            cacheList.add(tb); 
106.        } 
107.        return cacheList; 
108.    } 
109.        
110.    /**  
111.     * 创建整个Excel表  
112.     * @throws SQLException   
113.     *  
114.     */   
115.    public  void createExcelSheet() throws SQLException{ 
116.        createTableHeader();    
117.        int rowIndex=1; 
118.         
119.        List<Cachetable> list=getDate(); 
120.         
121.        for(int j=0;j<list.size();j++){ 
122.            List<String> listRead=new ArrayList<String>(); 
123.        for(int i=1;i<=columNumber;i++){ 
124.          listRead.add(list.get(i).getDevIp()); 
125.          listRead.add(list.get(i).getSrcaddr()); 
126.          listRead.add(list.get(i).getDstaddr()); 
127.          listRead.add(list.get(i).getNexthop()); 
128.          listRead.add(list.get(i).getInput()); 
129.          listRead.add(list.get(i).getOutput()); 
130.          listRead.add(list.get(i).getDpkts()); 
131.          listRead.add(list.get(i).getDoctets()); 
132.          listRead.add(list.get(i).getSstart()); 
133.          listRead.add(list.get(i).getProt()); 
134.          listRead.add(list.get(i).getTos()); 
135.          listRead.add(list.get(i).getSrcas()); 
136.          listRead.add(list.get(i).getDstas()); 
137.          listRead.add(list.get(i).getPduversion()); 
138.          listRead.add(rowIndex+""); 
139.        } 
140.         createTableRow(listRead,(short)rowIndex);    
141.         rowIndex++;    
142.        } 
143.    } 
144.    
145.    /**  
146.     * 导出表格  
147.     * @param sheet  
148.     * @param os  
149.     * @throws IOException  
150.     */   
151.    public void exportExcel(HSSFSheet sheet,OutputStream os) throws IOException    
152.    {    
153.        sheet.setGridsPrinted(true);    
154.        HSSFFooter footer = sheet.getFooter();    
155.        footer.setRight("Page " + HSSFFooter.page() + " of " +    
156.        HSSFFooter.numPages());    
157.        demoWorkBook.write(os);    
158.    }    
159.        
160.    public static void main(String[] args) {    
161.        String fileName = "f:\\世界五百强企业名次表.xls";    
162.         FileOutputStream fos = null;    
163.            try { 
164.                ExcelOut pd = new ExcelOut(); 
165.                pd.createExcelSheet(); 
166.                fos = new FileOutputStream(fileName);   
167.                pd.exportExcel(demoSheet,fos); 
168.                JOptionPane.showMessageDialog(null, "表格已成功导出到 : "+fileName); 
169.            } catch (Exception e) { 
170.                JOptionPane.showMessageDialog(null, "表格导出出错,错误信息 :"+e+"\n错误原因可能是表格已经打开。"); 
171.                e.printStackTrace(); 
172.            } finally { 
173.                try { 
174.                    fos.close();    
175.                } catch (Exception e) {    
176.                    e.printStackTrace();    
177.                }    
178.            }    
179.    }    
180.}   





说明:

   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类的有关消息输出的好处,很方便使用
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics