| - workbook
| ---- sheet
| ------- row
| ---------- celljava
workbook就至關於xls文件(在excel中稱之爲工做簿),一個workbook(工做簿)裏能夠有多個sheet(工做表),每一個工做表裏又分爲多個row(行),而每一個行中又有不少cell(單元格)。函數
public class Demo { public static void main(String[] args) { // 1. 建立workbook HSSFWorkbook workbook = new HSSFWorkbook(); // 2. 建立工做表 HSSFSheet sheet = workbook.createSheet("我是第一個工做表"); // 3. 建立行 HSSFRow row = sheet.createRow(0); // 4. 建立單元格 HSSFCell cell = row.createCell(0); // 5. 爲單元格設置內容 cell.setCellValue("這是A1單元格"); // 6. 全部內容設置完畢,導出xls文件 try { FileOutputStream fileOutputStream = new FileOutputStream("F:/demo.xls"); workbook.write(fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
HSSFCellStyle cellStyle = workbook.createCellStyle(); // 設置上下左右邊框 cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 設置字體 HSSFFont cellFont = workbook.createFont(); cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 加粗 cellFont.setFontName("微軟雅黑"); // 字體 cellFont.setFontHeightInPoints(((short) 12)); // 字號 cellFont.setColor(HSSFColor.BLUE.index); // 顏色 // 將字體綁定到樣式中 cellStyle.setFont(cellFont); // 設置對齊方式 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 設置單元格顏色 cellStyle.setFillForegroundColor(HSSFColor.RED.index); cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 設置自動換行 cellStyle.setWrapText(true); // 爲單元格設置樣式 cell.setCellStyle(cellStyle);
顏色樣式具體參見:http://blog.csdn.net/hantiannan/article/details/5312133字體
特別注意:如文章中的顏色爲HSSFColor.RED
,參數須要傳入HSSFColor.RED.index
url
// 設置列寬 sheet.setColumnWidth(0, 20 * 256); // 設置行高 row.setHeightInPoints(92f);
其中行高能夠使用上面的函數,參數爲像素值。.net
但列寬沒有提供設置像素值的參數,該函數的第一個參數表示列號(從0開始),第二個參數的單位是1/256個字符寬度,如上面代碼,則列寬爲20個字符的寬度。excel
CellRangeAddress cra = new CellRangeAddress(1, 3, 1, 6); sheet.addMergedRegion(cra);
其中第一個參數表示開始行,第二個參數表示結束行,第三個參數表示開始列,第四個參數表示結束列code
// 添加超連接 HSSFHyperlink hyperlink = new HSSFHyperlink(Hyperlink.LINK_DOCUMENT); hyperlink.setAddress("#" + "我是第一個工做表" + "!B1"); // # 後跟 表名, ! 後跟 單元格位置 cell.setHyperlink(hyperlink); // 設置超連接樣式 HSSFCellStyle hyperStyle = sheet.getWorkbook().createCellStyle(); HSSFFont hyperFont = workbook.createFont(); hyperFont.setUnderline((byte) 1); hyperFont.setColor(HSSFColor.BLUE.index); hyperFont.setFontName("微軟雅黑"); hyperFont.setFontHeightInPoints(((short) 12)); hyperStyle.setFont(hyperFont); cell.setCellStyle(hyperStyle);
// 代碼片斷,所有請仿照 工做簿內的超連接 代碼 HSSFHyperlink hyperlink = new HSSFHyperlink(Hyperlink.LINK_URL); hyperlink.setAddress("http://www.baidu.com"); // url
還支持email和文件,這裏就不介紹了。blog
以上是本次使用時的總結,POI很是強大,因爲水平有限只能總結這些,但足夠日常使用參考。圖片