關于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表格就介紹到這裡,還有其他需要設定表格格式,設定标題,設定其他單元格屬性的,可以參考官方文檔。