- 浏览: 87115 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
qintengfei:
不错,问题解决了。
ResultSet转换为List的方法 -
weichen:
看完之后挺管用,拿来试试人人网,大部分应用都能进,但是游戏中的 ...
HttpClient -
nggno1:
学习了~
Date类学习总结 -
chen88358323:
httpclient.getConnectionManager ...
HttpClient关于下载的资料收集 -
Eric_2007:
最后一条,有点过份!
一个女生看了会哭,男生会沉默的故事
一.POI简介
Jakarta POI 是apache的子项目,目标是处理ole2对象。它提供了一组操纵Windows文档的Java API
目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。
二.HSSF概况
HSSF 是Horrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。 也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。
HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。前者很好理解,后者比较抽象,但操作效率要高得多。
三.开始编码
1 ). 准备工作
要求:JDK 1.4+POI开发包
可以到 http://www.apache.org/dyn/closer.cgi/jakarta/poi/ 最新的POI工具包
2 ). EXCEL 结构
HSSFWorkbook excell 文档对象介绍
HSSFSheet excell的表单
HSSFRow excell的行
HSSFCell excell的格子单元
HSSFFont excell字体
HSSFName 名称
HSSFDataFormat 日期格式
在poi1.7中才有以下2项:
HSSFHeader sheet头
HSSFFooter sheet尾
和这个样式
HSSFCellStyle cell样式
辅助操作包括
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表
3 ).具体用法实例 (采用 usermodel )
如何读Excel
读取Excel文件时,首先生成一个POIFSFileSystem对象,由POIFSFileSystem对象构造一个HSSFWorkbook,该HSSFWorkbook对象就代表了Excel文档。下面代码读取上面生成的Excel文件写入的消息字串:
POIFSFileSystemfs=newPOIFSFileSystem(new FileInputStream("d:\test.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
String msg = cell.getStringCellValue();
如何写excel,
将excel的第一个表单第一行的第一个单元格的值写成“a test”。
POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream("workbook.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short)0);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
4) .相关方法介绍
New Workbook
New Sheet
Creating Cells
Creating Date Cells
Working with different types of cells
Demonstrates various alignment options
Working with borders
Iterate over rows and cells
Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. This is possible with a simple for loop.
Luckily, this is very easy. Row defines a CellIterator inner class to handle iterating over the cells (get one with a call to row.cellIterator()), and Sheet provides a rowIterator() method to give an iterator over all the rows.
Alternately, Sheet and Row both implement java.lang.Iterable, so if you're using Java 1.5, you can simply take advantage of the built in "foreach" support - see below.
Sheet sheet = wb.getSheetAt(0); for (Iterator rit = sheet.rowIterator(); rit.hasNext(); ) { Row row = (Row)rit.next(); for (Iterator cit = row.cellIterator(); cit.hasNext(); ) { Cell cell = (Cell)cit.next(); // Do something here } } HSSFSheet sheet = wb.getSheetAt(0); for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) { HSSFRow row = rit.next(); for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) { HSSFCell cell = cit.next(); // Do something here } }Iterate over rows and cells using Java 1.5 foreach loops
Sometimes, you'd like to just iterate over all the rows in a sheet, or all the cells in a row. If you are using Java 5 or later, then this is especially handy, as it'll allow the new foreach loop support to work.
Luckily, this is very easy. Both Sheet and Row implement java.lang.Iterable to allow foreach loops. For Row this allows access to the CellIterator inner class to handle iterating over the cells, and for Sheet gives the rowIterator() to iterator over all the rows.
Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { // Do something here } }Getting the cell contents
To get the contents of a cell, you first need to know what kind of cell it is (asking a string cell for its numeric contents will get you a NumberFormatException for example). So, you will want to switch on the cell's type, and then call the appropriate getter for that cell.
In the code below, we loop over every cell in one sheet, print out the cell's reference (eg A3), and then the cell's contents.
// import org.apache.poi.ss.usermodel.*; Sheet sheet1 = wb.getSheetAt(0); for (Row row : sheet1) { for (Cell cell : row) { CellReference cellRef = new CellReference(row.getRowNum(), cell.getCellNum()); System.out.print(cellRef.formatAsString()); System.out.print(" - "); switch(cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.println(cell.getRichStringCellValue().getString()); break; case Cell.CELL_TYPE_NUMERIC: if(DateUtil.isCellDateFormatted(cell)) { System.out.println(cell.getDateCellValue()); } else { System.out.println(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println(); } } }Text Extraction
For most text extraction requirements, the standard ExcelExtractor class should provide all you need.
InputStream inp = new FileInputStream("workbook.xls"); HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp)); ExcelExtractor extractor = new ExcelExtractor(wb); extractor.setFormulasNotResults(true); extractor.setIncludeSheetNames(false); String text = extractor.getText();For very fancy text extraction, XLS to CSV etc, take a look at /src/scratchpad/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java
Fills and colors
Merging cells
Working with fonts
Note, the maximum number of unique fonts in a workbook is limited to 32767 ( the maximum positive short). You should re-use fonts in your apllications instead of creating a font for each cell. Examples:
Wrong:
for (int i = 0; i < 10000; i++) { Row row = sheet.createRow(i); Cell cell = row.createCell((short) 0); CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); cell.setCellStyle(style); }Correct:
CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); for (int i = 0; i < 10000; i++) { Row row = sheet.createRow(i); Cell cell = row.createCell((short) 0); cell.setCellStyle(style); }Custom colors
HSSF:
HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); HSSFRow row = sheet.createRow((short) 0); HSSFCell cell = row.createCell((short) 0); cell.setCellValue("Default Palette"); //apply some colors from the standard palette, // as in the previous examples. //we'll use red text on a lime background HSSFCellStyle style = wb.createCellStyle(); style.setFillForegroundColor(HSSFColor.LIME.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); HSSFFont font = wb.createFont(); font.setColor(HSSFColor.RED.index); style.setFont(font); cell.setCellStyle(style); //save with the default palette FileOutputStream out = new FileOutputStream("default_palette.xls"); wb.write(out); out.close(); //now, let's replace RED and LIME in the palette // with a more attractive combination // (lovingly borrowed from freebsd.org) cell.setCellValue("Modified Palette"); //creating a custom palette for the workbook HSSFPalette palette = wb.getCustomPalette(); //replacing the standard red with freebsd.org red palette.setColorAtIndex(HSSFColor.RED.index, (byte) 153, //RGB red (0-255) (byte) 0, //RGB green (byte) 0 //RGB blue ); //replacing lime with freebsd.org gold palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102); //save with the modified palette // note that wherever we have previously used RED or LIME, the // new colors magically appear out = new FileOutputStream("modified_palette.xls"); wb.write(out); out.close();XSSF:
XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet(); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell( 0); cell.setCellValue("custom XSSF colors"); XSSFCellStyle style1 = wb.createCellStyle(); style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128))); style1.setFillPattern(CellStyle.SOLID_FOREGROUND);Reading and Rewriting Workbooks
Using newlines in cells
Data Formats
Fit Sheet to One Page
Set Print Area
Set Page Numbers on Footer
Using the Convenience Functions
The convenience functions live in contrib and provide utility features such as setting borders around merged regions and changing style attributes without explicitly creating new styles.
HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet1 = wb.createSheet( "new sheet" ); // Create a merged region HSSFRow row = sheet1.createRow( (short) 1 ); HSSFRow row2 = sheet1.createRow( (short) 2 ); HSSFCell cell = row.createCell( (short) 1 ); cell.setCellValue( "This is a test of merging" ); Region region = new Region( 1, (short) 1, 4, (short) 4 ); sheet1.addMergedRegion( region ); // Set the border and border colors. final short borderMediumDashed = HSSFCellStyle.BORDER_MEDIUM_DASHED; HSSFRegionUtil.setBorderBottom( borderMediumDashed, region, sheet1, wb ); HSSFRegionUtil.setBorderTop( borderMediumDashed, region, sheet1, wb ); HSSFRegionUtil.setBorderLeft( borderMediumDashed, region, sheet1, wb ); HSSFRegionUtil.setBorderRight( borderMediumDashed, region, sheet1, wb ); HSSFRegionUtil.setBottomBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setTopBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setLeftBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); HSSFRegionUtil.setRightBorderColor(HSSFColor.AQUA.index, region, sheet1, wb); // Shows some usages of HSSFCellUtil HSSFCellStyle style = wb.createCellStyle(); style.setIndention((short)4); HSSFCellUtil.createCell(row, 8, "This is the value of the cell", style); HSSFCell cell2 = HSSFCellUtil.createCell( row2, 8, "This is the value of the cell"); HSSFCellUtil.setAlignment(cell2, wb, HSSFCellStyle.ALIGN_CENTER); // Write out the workbook FileOutputStream fileOut = new FileOutputStream( "workbook.xls" ); wb.write( fileOut ); fileOut.close();Shift rows up or down on a sheet
Set a sheet as selected
Set the zoom magnification
The zoom is expressed as a fraction. For example to express a zoom of 75% use 3 for the numerator and 4 for the denominator.
Workbook wb = new HSSFWorkbook(); Sheet sheet1 = wb.createSheet("new sheet"); sheet1.setZoom(3,4); // 75 percent magnificationSplits and freeze panes
There are two types of panes you can create; freeze panes and split panes.
A freeze pane is split by columns and rows. You create a freeze pane using the following mechanism:
sheet1.createFreezePane( 3, 2, 3, 2 );
The first two parameters are the columns and rows you wish to split by. The second two parameters indicate the cells that are visible in the bottom right quadrant.
Split pains appear differently. The split area is divided into four separate work area's. The split occurs at the pixel level and the user is able to adjust the split by dragging it to a new position.
Split panes are created with the following call:
sheet2.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
The first parameter is the x position of the split. This is in 1/20th of a point. A point in this case seems to equate to a pixel. The second parameter is the y position of the split. Again in 1/20th of a point.
The last parameter indicates which pane currently has the focus. This will be one of Sheet.PANE_LOWER_LEFT, PANE_LOWER_RIGHT, PANE_UPPER_RIGHT or PANE_UPPER_LEFT.
Workbook wb = new HSSFWorkbook(); Sheet sheet1 = wb.createSheet("new sheet"); Sheet sheet2 = wb.createSheet("second sheet"); Sheet sheet3 = wb.createSheet("third sheet"); Sheet sheet4 = wb.createSheet("fourth sheet"); // Freeze just one row sheet1.createFreezePane( 0, 1, 0, 1 ); // Freeze just one column sheet2.createFreezePane( 1, 0, 1, 0 ); // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). sheet3.createFreezePane( 2, 2 ); // Create a split with the lower left side being the active quadrant sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT ); FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();Repeating rows and columns
It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the HSSFWorkbook class.
This function Contains 5 parameters. The first parameter is the index to the sheet (0 = first sheet). The second and third parameters specify the range for the columns to repreat. To stop the columns from repeating pass in -1 as the start and end column. The fourth and fifth parameters specify the range for the rows to repeat. To stop the columns from repeating pass in -1 as the start and end rows.
Workbook wb = new HSSFWorkbook(); Sheet sheet1 = wb.createSheet("new sheet"); Sheet sheet2 = wb.createSheet("second sheet"); // Set the columns to repeat from column 0 to 2 on the first sheet wb.setRepeatingRowsAndColumns(0,0,2,-1,-1); // Set the the repeating rows and columns on the second sheet. wb.setRepeatingRowsAndColumns(1,4,5,1,2); FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();Headers and Footers
Example is for headers but applies directly to footers.
Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("new sheet"); Header header = sheet.getHeader(); header.setCenter("Center Header"); header.setLeft("Left Header"); header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16"); FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();发表评论
-
工作记录
2010-03-08 11:26 773sqlserver2000 安装报注册表挂起解决: ... -
利用ftp服务器实现文件上传下载
2009-08-12 12:09 1512利用ftp服务器实现文件 ... -
hibernate 多条件组合查询 之 sql 拼接
2009-08-10 15:38 1867public static void main(String[ ... -
工作记录
2009-06-16 18:13 7681 用PrintWriter对象写文件 StringB ... -
控件通知消息
2009-05-05 13:49 18972008年04月06日 星期日 00:09 控件通知消 ... -
Hibernate的检索策略
2009-05-04 13:54 744Hibernate的检索策略包括类级别检索策略和关联级别检索策 ... -
ResultSet转换为List的方法
2009-04-11 20:39 2509ResultSet转换为List的方法 private s ... -
文件批量上传
2009-03-23 17:06 1145执行类: /** * @author LX ... -
工作异常记录
2009-03-20 18:44 8031 hbm.xml配置问题 org.springframewo ... -
Date类学习总结
2009-03-06 13:34 9521.计算某一月份的最大天数 Calendar time=Cal ... -
java日期(Date)、日历(Calendar)、日期格式(DateFormat)三类介绍
2009-02-16 13:45 2699语言的Calendar(日历),Date(日期), 和Date ... -
关于日期格式的一些记录
2009-02-16 13:43 887一、自定义月份: Date aDate = new Dat ... -
JAVA正则表达式4种常用功能
2009-02-12 10:31 915JAVA正则表达式4种常 ... -
list排序
2009-02-06 11:28 1048import java.text.Collator; ... -
java中删除一个非空目录的方法
2009-02-04 19:03 2942在java中没有直接删除非空目录的方法,所以要自己编写方法来删 ... -
List与数组实体的转换
2009-01-22 17:41 12431.List转换成为数组。(这里的List是实体是ArrayL ... -
HttpClient认证(3)
2009-01-15 10:59 1350清单 2. 在 HttpClient 中自定义 SSL 示例 ... -
HttpClient认证(2)
2009-01-15 10:47 2338Form-Based 认证方式在 J2EE 站点中更为常见。这 ... -
HttpClient认证(1)
2009-01-15 10:29 1450J2EE 站点认证简介 出于安全性的需要和用户授权管理的考虑 ... -
HttpClient 学习整理(4)
2009-01-15 10:05 15445. 提交XML格式参数
相关推荐
HSSF提供对低级别的记录和事件模型的访问,而XSSF则基于SXSSF(Streaming Usermodel API)提供了内存优化的模型,适用于大型工作簿。 2. **SS.usermodel**: 这是用于处理Excel文档的用户模型接口,包括工作簿...
HSSF提供对低级别的记录和流操作的支持,而XSSF则更适应XML结构的xlsx文件。 1. HSSF(Horrible Spreadsheet Format):HSSF是Apache POI中用于处理Excel 97-2003二进制文件格式(.xls)的部分。它允许创建、修改和...
HSSF接口提供了丰富的API,可以创建新的工作簿、工作表,添加单元格,设置样式,以及读取和修改现有Excel文件中的数据。与简单的CSV格式相比,使用POI能够创建具有复杂格式、公式和图表的真正Excel对象,这使得它在...
Apache POI提供了HSSF(Horrible Spreadsheet Format)和XSSF(XML Spreadsheet Format)两个接口,分别用于处理老版本的.xls和新版本的.xlsx文件。 通用工具类的核心功能包括: 1. **创建工作簿对象**:使用`...
`LogsServicei.java`可能是项目中用于记录日志的服务类,可能与Apache POI 的操作相关联,记录处理Office文档过程中的信息。 `ajax_百度百科.mht`和`Apache POI_百度百科.mht`是关于Ajax技术和Apache POI 的百科...
1. **HSSF (Horrible Spreadsheet Format)**:这是处理旧版Excel文件(.xls)的库,基于低级记录格式。HSSF提供了对单元格样式、公式、图表等的支持。 2. **XSSF (XML Spreadsheet Format)**:用于处理Excel 2007及...
POI项目由Apache软件基金会维护,为开发者提供了在Java应用程序中读取、写入和修改这些文件的接口。POI 3.8和3.9版本是该库的两个稳定版本,它们包含了一系列API,使得开发人员可以轻松地与微软的Office格式进行交互...
在本组件中,开发者可能使用了HSSF(Horrible Spreadsheet Format)处理老版本的Excel(.xls)文件,或者使用XSSF(XML Spreadsheet Format)处理新版本的Excel(.xlsx)文件。 2. **数据转换**: - 对象映射:将...
它包括HSSF(Horrible Spreadsheet Format)用于处理.xls文件,以及XSSF(XML Spreadsheet Format)用于处理.xlsx文件。 2. **JODConverter**:这是一个基于OpenOffice的工具,可以将一种办公格式转换为另一种,...
最后,程序可能还需要提供错误处理和日志记录机制,以便在导入过程中遇到问题时能够及时发现并解决。 综上所述,这个Java小程序涵盖了数据库连接、用户界面设计、Excel文件操作、数据验证、批量处理、事务管理和...
- 错误记录:记录失败的导入操作,便于后期分析和修复。 - 性能优化:根据具体情况调整批量插入的大小,平衡性能和内存占用。 通过学习和实践这个demo,你不仅可以掌握使用Apache POI处理Excel的基本技巧,还能了解...
首先,UserModel模型,也称为HSSF/SS.usermodel,是POI的核心部分,它允许开发者完全控制Excel文件的每一个细节。通过UserModel,你可以创建新的工作簿、工作表,添加单元格、公式,甚至自定义样式。然而,这个模型...
开发者通过学习和理解这些源码,可以自定义转换逻辑,适应特定的业务需求,比如增加特定的转换选项、集成到自动化工作流中,或者调整性能参数。 总之,这个源码为开发者提供了一种解决方案,使他们能够高效地将...
9. **日志记录**:通过日志框架(如Logback或Log4j),我们可以记录导入过程中的关键信息,帮助调试和追踪问题。 10. **安全性考虑**:考虑到文件上传可能的安全风险,如病毒或恶意代码,我们还需要对上传的文件...
处理大量数据时,使用SXSSF(Streaming Usermodel API)比使用常规的HSSF或XSSF更合适。SXSSF在磁盘上保持工作簿的临时状态,以防止内存溢出。这种方式允许在内存有限的情况下处理大量记录。 3. **分批写入**: ...
`org.apache.poi` 包含了 `HSSF`(旧版Excel)和 `XSSF`(新版Excel)接口,用于读写Excel数据。 12. **进程**: `java.lang.ProcessBuilder` 和 `java.lang.Process` 用于创建和管理操作系统进程,可以执行外部命令...
1. **POI API大全**:POI提供了一系列的类和接口,例如`HSSFWorkbook`和`XSSFWorkbook`用于处理Excel的HSSF(旧版的Excel 97-2003)和XSSF(用于Excel 2007及以上版本)格式。对于Word,有`HWPFDocument`和`...