JAVA用POI讀取和創建2003和2007版本Excel


1.添加maven依賴

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.10-FINAL</version>
        </dependency>

2.讀取和創建2003和2007版本Excel示例

 1 package com.wyg.simple;  2 
 3 import java.io.File;  4 import java.io.FileInputStream;  5 import java.io.FileOutputStream;  6 import java.io.IOException;  7 import java.text.DecimalFormat;  8 import java.text.SimpleDateFormat;  9 import java.util.LinkedList;  10 import java.util.List;  11 
 12 import org.apache.poi.hssf.usermodel.HSSFCellStyle;  13 import org.apache.poi.hssf.usermodel.HSSFDataFormat;  14 import org.apache.poi.hssf.usermodel.HSSFDateUtil;  15 import org.apache.poi.hssf.usermodel.HSSFFont;  16 import org.apache.poi.hssf.usermodel.HSSFWorkbook;  17 import org.apache.poi.hssf.util.HSSFColor;  18 import org.apache.poi.ss.usermodel.Cell;  19 import org.apache.poi.ss.usermodel.CellStyle;  20 import org.apache.poi.ss.usermodel.Font;  21 import org.apache.poi.ss.usermodel.Row;  22 import org.apache.poi.ss.usermodel.Sheet;  23 import org.apache.poi.ss.usermodel.Workbook;  24 import org.apache.poi.xssf.usermodel.XSSFCell;  25 import org.apache.poi.xssf.usermodel.XSSFWorkbook;  26 
 27 public class CreatAndReadExcel {  28     private static String excel2007Path = "D:\\temp\\style_2007.xlsx";  29     private static String excel2003Path = "D:\\temp\\style_2003.xls";  30 
 31     public static void main(String[] args) throws Exception {  32         creatExcel(excel2007Path, "2007");// 創建2007版Excel文件
 33         creatExcel(excel2003Path,"2003");// 創建2003版Excel文件  34 
 35 // List<List<Object>> excel2007List = readExcel(excel2007Path);// 讀取2007版Excel文件
 36         List<List<Object>> excel2003List = readExcel(excel2003Path);// 讀取2003版Excel文件
 37  System.out.println(excel2003List.toString());  38  }  39 
 40     /**
 41  * 創建Excel文件  42  *  43  * @return
 44  * @throws IOException  45      */
 46     public static void creatExcel(String excelPath, String version) throws IOException {  47         // XSSFWork used for .xslx (>=2007), HSSWorkbook for 03 .xsl
 48         Workbook workbook = null;  49         if (version.equals("2007")) {  50             workbook = new XSSFWorkbook();// 創建 一個excel文檔對象
 51         } else if (version.equals("2003")) {  52             workbook = new HSSFWorkbook();// 創建 一個excel文檔對象
 53  }  54         Sheet sheet = workbook.createSheet("2007sheet");// 創建一個工作薄對象
 55         sheet.setColumnWidth(1, 10000);// 設置第二列的寬度為
 56 
 57         Row row0 = sheet.createRow(1);// 創建一個行對象,從0行開始
 58         row0.setHeightInPoints(23);// 設置行高23像素
 59         for (int i = 0; i < 11; i++) {  60             Cell cell_1 = row0.createCell(i, Cell.CELL_TYPE_STRING);// 創建單元格,從0列開始
 61             cell_1.setCellValue("column" + i);// 寫入單元格的值
 62             CellStyle style = getStyle(workbook);  63             cell_1.setCellStyle(style);// 應用樣式對象
 64             sheet.autoSizeColumn(i);// 自動調整列寬
 65  }  66 
 67         FileOutputStream outputStream = new FileOutputStream(excelPath);  68         workbook.write(outputStream);// 將文檔對象寫入文件輸出流
 69 
 70         outputStream.close();// 關閉文件輸出流
 71         System.out.println("創建成功 office excel");  72  }  73 
 74     /**
 75  * 設置樣式  76  *  77  * @param workbook  78  * @return
 79      */
 80     private static CellStyle getStyle(Workbook workbook) {  81         CellStyle style = workbook.createCellStyle();// 創建樣式對象  82         // 設置對齊方式
 83         style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中
 84         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中  85 
 86         // 設置邊框
 87         style.setBorderTop(HSSFCellStyle.BORDER_THICK);// 頂部邊框粗線
 88         style.setTopBorderColor(HSSFColor.RED.index);// 設置為紅色
 89         style.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);// 底部邊框雙線
 90         style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);// 左邊邊框
 91         style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);// 右邊邊框
 92 
 93         style.setWrapText(true);// 設置單元格內容是否自動換行  94         // 格式化日期
 95         style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  96 
 97         // 設置單元格字體
 98         Font font = workbook.createFont(); // 創建字體對象
 99         font.setFontHeightInPoints((short) 14);// 設置字體大小
100         font.setColor(HSSFColor.RED.index);// 設置字體顏色
101         font.setFontName("宋體");// 設置為宋體字
102         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設置粗體
103         style.setFont(font);// 將字體加入到樣式對象
104 
105         return style; 106  } 107 
108     /**
109  * 讀取excel 110  * 111  * @param fileName 112  * @return 行<列> 113  * @throws IOException 114      */
115 
116     private static List<List<Object>> readExcel(String fileName) throws IOException { 117         File file = new File(fileName); 118         Workbook wb = null; 119         if (fileName.endsWith(".xlsx")) {// 2007
120             wb = new XSSFWorkbook(new FileInputStream(file));// 創建 一個excel文檔對象
121         } else if (fileName.endsWith(".xls")) {// 2003
122             wb = new HSSFWorkbook(new FileInputStream(file));// 創建 一個excel文檔對象
123  } 124 
125         Sheet sheet = wb.getSheetAt(0);// 讀取第一個sheet頁表格內容
126         Object value = null; 127         Row row = null; 128         Cell cell = null; 129         System.out.println("讀取office 2007 excel內容如下:"); 130 // System.out.println(sheet.getPhysicalNumberOfRows());// 獲取的是物理行數,也就是不包括那些空行(隔行)的情況。 131 // System.out.println(sheet.getLastRowNum());// 獲取的是最后一行的編號(編號從0開始) 132         //
133         List<List<Object>> rowlist = new LinkedList<List<Object>>(); 134         for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { 135             row = sheet.getRow(i); 136             if (row == null) { 137                 continue; 138  } 139 
140             //
141             List<Object> cellList = new LinkedList<Object>(); 142             for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) { 143                 cell = row.getCell(j); 144                 if (cell == null) { 145                     continue; 146  } 147 
148                 DecimalFormat df = new DecimalFormat("0");// 格式化 number String
149                 DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字
150                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
151                 switch (cell.getCellType()) { 152                     case XSSFCell.CELL_TYPE_STRING:// 字符串——String type
153                         value = cell.getStringCellValue(); 154                         break; 155                     case XSSFCell.CELL_TYPE_NUMERIC:// 數字——Number type
156                         if ("@".equals(cell.getCellStyle().getDataFormatString())) { 157                             value = df.format(cell.getNumericCellValue()); 158                         } else if ("General".equals(cell.getCellStyle().getDataFormatString())) { 159                             value = nf.format(cell.getNumericCellValue()); 160                         } else { 161                             value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())); 162  } 163                         break; 164                     case XSSFCell.CELL_TYPE_BOOLEAN:// boolean——Boolean type
165                         value = cell.getBooleanCellValue(); 166                         break; 167                     case XSSFCell.CELL_TYPE_BLANK:// 空白——Blank type
168                         value = ""; 169                         break; 170                     default:// default type
171                         value = cell.toString(); 172  } 173                 if (value == null || "".equals(value)) { 174                     continue; 175  } 176  cellList.add(value); 177  } 178  rowlist.add(cellList); 179  } 180         return rowlist; 181  } 182 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM