关于Excel文件的操作,有很多的API,这里仅仅介绍Apache 的POI。其实具体更多的一些内容可以参考官网。我这里仅仅是一个快速的入门。
http://poi.apache.org/components/spreadsheet/quick-guide.html#Iterator
一 POI简介
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能
HSSF是POI项目的Excel '97(-2007)文件格式的纯Java实现。XSSF是POI Project的Excel 2007 OOXML(.xlsx)文件格式的纯Java实现。
HSSF和XSSF提供了阅读电子表格创建,修改,读取和写入XLS电子表格的方法。他们提供:
- 为特殊需要的人提供低水平的结构
- 一个eventmodel api,用于高效的只读访问
- 用于创建,读取和修改XLS文件的完整usermodel api
Excel的常用的操作
1、创建工作表。
具体的流程是;首先创建一个Excel的文件workbook.xls。使用java 的IO就可以创建。接下来创建一个工作表sheet。然后创建一行Row 。创建行后创建一个单元格cell。单元格创建好之后可以修改单元格中的值。还可以通过创建单元格的格式使得单元格中的值遵循某种样式。比如日期格式
//创建一个工作表。.xls 和 .xlsx
public void creatWorkbook(){
Workbook wb=new HSSFWorkbook();
try {
OutputStream fileOut=new FileOutputStream("workbook.xls");
CreationHelper createHelper = wb.getCreationHelper();
//创建工作表
Sheet sheet=wb.createSheet("new sheet");
//创建一行并在其中放入一些单元格。行数是0
Row row = sheet.createRow(0);
//创建一个单元格并在其中放入一个值
Cell cell = row.createCell(0);
cell.setCellValue(1);
//或者在一行创建创建一些值
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("this is a string"));
row.createCell(3).setCellValue(true);
//创建日期单元格
cell.setCellValue(new Date()); //该格式有误
//我们将第二个单元格设置为日期(和时间)。重要的是
//从工作簿中创建一个新的单元格样式,否则你最终可能
//修改内置样式并不仅影响这个单元格而且影响其他单元格。
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(4);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
//也可以使用java的内置的日期格式calender
cell = row.createCell(5);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);
wb.write(fileOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2、读取工作表的内容
//读取Excel的表格
public void getCell() {
DataFormatter formatter = new DataFormatter();
InputStream is=null;
Workbook wb = null;
try {
//读文件
is = new FileInputStream("e:/workspace/test/workbook.xls");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wb = new HSSFWorkbook(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Sheet sheet1 = wb.getSheetAt(0);
//得到总行数
int rowNum = sheet1.getLastRowNum();
for (Row row : sheet1) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
System.out.print(cellRef.formatAsString());
System.out.print(cell);
// get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
String text = formatter.formatCellValue(cell);
System.out.println(text);
// Alternatively, get the value and format it yourself
}
}
}
关于Excel表格就介绍到这里,还有其他需要设置表格格式,设置标题,设置其他单元格属性的,可以参考官方文档。