Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。
接口:
HSSF - Microsoft Excel
XSSF - Microsoft Excel OOXML(07以上版本)
HWPF - Microsoft Word
HSLF - Microsoft PowerPoint
HDGF - Microsoft Visio
EXCEL 結構:
HSSFWorkbook excell文檔對象
HSSFSheet excell的表單
HSSFRow excell的行
HSSFCell excell的格子單元
HSSFFont excell字體
HSSFName 名稱
HSSFDataFormat 日期格式
讀Excel
讀取Excel文件時,首先生成一個POIFSFileSystem對象,由POIFSFileSystem對象構造一個HSSFWorkbook,該HSSFWorkbook對象就表明了Excel文檔
代碼:
FileInputStream is = new FileInputStream("test.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
String msg = cell.getStringCellValue();
寫Excel
FileInputStream is = new FileInputStream("test.xls");
POIFSFileSystem fs = new POIFSFileSystem(is);
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");
FileOutputStream os = new FileOutputStream("test.xls ");
wb.write(os);
os.close();
設置行高、列寬
sheet.setColumnWidth(0, 10000);
row.setHeight((short) 1000);
設置字號、顏色和內容位置
HSSFCellStyle style = wb.createCellStyle();
HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 14);
f.setColor(HSSFFont.COLOR_RED);
style.setFont(f);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
合併單元格 sheet.addMergedRegion(new Region(1, (short) 1, 2, (short) 2));