您的位置:首页 > 编程语言 > Java开发

java 使用 poi 操纵 excel2003 经验总结

2012-10-26 16:21 405 查看
poi简介:

  Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 POI 的功能。

结构

HSSF - 提供读写Microsoft Excel XLS格式档案的功能。

XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。

HWPF - 提供读写Microsoft Word DOC格式档案的功能。

HSLF - 提供读写Microsoft PowerPoint格式档案的功能。

HDGF - 提供读Microsoft Visio格式档案的功能。

HPBF - 提供读Microsoft Publisher格式档案的功能。

HSMF - 提供读Microsoft Outlook格式档案

操纵excel2003的类大多在hssf包中。

由于poi只提供了复制sheet的方法没有提供复制row的方法,在这里先贴出复制row的方法,以便今后查阅使用。

样式

//获取单元格一般样式的方法:
HSSFCellStyle cellstyle    ;                                        //单元格样式
cellstyle = cell.getCellStyle();                                //获取cellstyle
short borderBottom = cellstyle.getBorderBottom();                //下边框
short borderLeft = cellstyle.getBorderLeft();                    //左边框
short borderRight = cellstyle.getBorderRight();                    //右边框
short borderTop = cellstyle.getBorderTop();                        //上边框
short background = cellstyle.getFillBackgroundColor();            //背景色
short foreground = cellstyle.getFillForegroundColor();            //前景色
short alignment = cellstyle.getAlignment();                        //水平对齐
short verAlignment = cellstyle.getVerticalAlignment();             //垂直对齐
boolean wrapText = cellstyle.getWrapText();                        //自动换行
HSSFFont font = cellstyle.getFont(wb);                            //Font
short color = font.getColor();                                    //颜色
String fontName = font.getFontName();                            //字体
short fontHeight = font.getFontHeightInPoints();                //字号
short boldWeight = font.getBoldweight();                        //字形
//对应的有相同的set方法


你也许在复制行的代码中注意到了,
在excel中日期也是以数字形式存储,
需要借助于HSSFDateUtil.isCellDateFormatted(cell)判断是否为日期型。
然后通过cell.getDateCellValue()来获取日期单元格的日期

如果你需要将excel的信息都存入数据库中,你也许需要将Date转成String:
Date D_temp = cell.getDateCellValue();
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS",java.util.Locale.US);//"yyyy-MM-dd HH:mm:ss SSS"可自行修改
String cellValue = sdf.format(D_temp);
回转:
Date D_temp = sdf.parse(cellValue);

有时需要获取行高和列宽:
row.getHeightInPoints(); //Excel获取行高所使用单位为Point(点)
sheet.getColumnWidth(colIndex); //列宽使用单位为Character(字符)的1/256
关于点,字符,像素的换算关系,本人没有弄透。
行高对应像素:Row Height(point)=Height Pixels * 0.75

在复制行的方法中,对于合并单元格应该很好理解。
合并单元格看做一个方形区域,用CellRangeAddress对象表示,它有4个属性:FirstRow,LastRow,FirstColumn,LastColumn
构造方法:CellRangeAddress cra = new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: