1. 程式人生 > >Java操作Excel之POI簡單例子

Java操作Excel之POI簡單例子

comm last pre cto ada tabs cnblogs encrypted hssf

 21 /**
 22  * 利用POI操作Excel表單
 23  * 
 24  * 需要jar包:
 25  *     HSSF針對03及以前版本,即.xls後綴
 26  *         |---poi-3.16.jar
 27  *     XSSF針對07及以後版本,即xlsx後綴
 28  *         |---poi-3.16.jar
 29  *         |---poi-ooxml.3.16.jar
 30  *         |---poi-ooxml-schemas-3.16.jar
 31  *         |---xmlbeans-2.6.0.jar
32 * |---commons-collections4-4.1.jar 33 * 34 * 工作簿:Workbook 35 * 工作表:Sheet 36 * 行: Row 37 * 表格:Cell 38 */ 39 public class Demo { 40 41 /** 42 * 讀取Excel表格 43 * @throws IOEception 44 * @throws InvalidFormatException 45 * @throws EncryptedDocumentException
46 */ 47 @Test 48 public void readExcel() throws EncryptedDocumentException, InvalidFormatException, IOException { 49 //工作簿 50 Workbook workbook = WorkbookFactory.create(new File("src/userExce1.xls")); 51 //工作表 52 Sheet sheet = workbook.getSheetAt(0); 53 //
54 Row row = sheet.getRow(1); 55 // 56 Cell cell = row.getCell(0); 57 58 System.out.println("表格值為:" + cell.getStringCellValue()); 59 } 60 61 /** 62 * 創建Excel表格 63 * @throws IOException 64 * @throws InvalidFormatException 65 * @throws EncryptedDocumentException 66 */ 67 @Test 68 public void writeExcel() throws EncryptedDocumentException, InvalidFormatException, IOException { 69 //工作簿 70 Workbook workbook = new XSSFWorkbook(); 71 //工作表 72 Sheet sheet = workbook.createSheet("我的第一個sheet"); 73 // 74 Row row = sheet.createRow(0); 75 // 76 Cell cell = row.createCell(3); 77 78 cell.setCellValue("哈哈表格插入一個內容"); 79 80 workbook.write(new FileOutputStream("c:/test.xlsx")); 81 } 82 83 /** 84 * 讀取Excel表格,修改樣式和內容並保存 85 * @throws IOEception 86 * @throws InvalidFormatException 87 * @throws EncryptedDocumentException 88 */ 89 @Test 90 public void readAndModifyExcel() throws EncryptedDocumentException, InvalidFormatException, IOException { 91 92 String filename = "src/userExcel.xlsx"; 93 File file = new File(filename); 94 95 System.out.println(file.getAbsolutePath()); 96 97 Workbook workbook = WorkbookFactory.create(file); 98 Sheet sheet = workbook.getSheetAt(0); 99 100 //合並單元格,在工作表添加合並單元格 101 CellRangeAddress headSpan = new CellRangeAddress(2, 2, 0, 4); 102 sheet.addMergedRegion(headSpan); 103 104 //在合並的位置設置表頭文字 105 Row row = sheet.createRow(0); 106 Cell cell = row.createCell(0); 107 cell.setCellValue("這是表頭"); 108 109 //寫入文本中 110 String savedName = filename.matches("\\S+\\.xls") ? "c:/" + filename.replace("src/", "") : "c:/" + filename.replace("src/", ""); 111 workbook.write(new FileOutputStream(savedName)); 112 } 113 114 }


excel基礎元素

工作簿
工作表(屬於工作簿)
行(屬於工作表)
單元格(屬於行;由行和列確定)

-------------操作excel
1、創建/讀取工作簿
2、創建/讀取工作表
3、創建/讀取行
4、創建/讀取單元格


-----------excel樣式

合並單元格對象(CellRangeAddress)屬於工作簿;運用於工作表

CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) 起始行號,結束行號,起始列號,結束列號


樣式是屬於工作簿的;運用於單元格

字體是屬於工作簿的;加載於樣式;通用樣式運用於單元格

Java操作Excel之POI簡單例子