1. 程式人生 > >【Java】使用Apache POI生成和解析Excel檔案

【Java】使用Apache POI生成和解析Excel檔案

概述

  Excel是我們平時工作中比較常用的用於儲存二維表資料的,JAVA也可以直接對Excel進行操作,分別有jxl和poi,2種方式。

程式碼

  要使用poi,必須引入poi的jar包,maven依賴如下(最新包可參考mvn資訊):

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>

<dependency
>
<groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version
>
3.14</version> </dependency>

  使用poi建立execl檔案
其中部分方法可以封裝,或者省略

package test.dzy.poi;

 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.Date;

 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache
.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; public class CreateExcel { public static void main(String[] args) throws IOException, InterruptedException { Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() }; for (int i = 0; i < wbs.length; i++) { Workbook workbook = wbs[i]; // 得到一個POI的工具類 CreationHelper createHelper = workbook.getCreationHelper(); // 在Excel工作簿中建一工作表,其名為預設值, 也可以指定Sheet名稱 Sheet sheet = workbook.createSheet(); // Sheet sheet = workbook.createSheet("SheetName"); // 用於格式化單元格的資料 DataFormat format = workbook.createDataFormat(); // 設定字型(可封裝) Font font = workbook.createFont(); font.setFontHeightInPoints((short) 20); // 字型高度 font.setColor(Font.COLOR_RED); // 字型顏色 font.setFontName("黑體"); // 字型 font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 寬度 font.setItalic(true); // 是否使用斜體 // font.setStrikeout(true); //是否使用劃線 // 設定單元格型別(可封裝) CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFont(font); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平佈局:居中 cellStyle.setWrapText(true); CellStyle cellStyle2 = workbook.createCellStyle(); cellStyle2.setDataFormat(format.getFormat("#, ## 0.0")); CellStyle cellStyle3 = workbook.createCellStyle(); cellStyle3.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm:ss")); // 新增單元格註釋(可封裝) // 建立Drawing物件,Drawing是所有註釋的容器. Drawing drawing = sheet.createDrawingPatriarch(); // ClientAnchor是附屬在WorkSheet上的一個物件, 其固定在一個單元格的左上角和右下角. ClientAnchor anchor = createHelper.createClientAnchor(); // 設定註釋位子(可封裝) anchor.setRow1(0); anchor.setRow2(2); anchor.setCol1(0); anchor.setCol2(2); // 定義註釋的大小和位置,詳見文件(可封裝) Comment comment = drawing.createCellComment(anchor); // 設定註釋內容 RichTextString str = createHelper.createRichTextString("Hello, World!"); comment.setString(str); // 設定註釋作者. 當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("H__D"); // 定義幾行 for (int rownum = 0; rownum < 30; rownum++) { // 建立行 Row row = sheet.createRow(rownum); // 建立單元格 Cell cell = row.createCell((short) 1); cell.setCellValue(createHelper.createRichTextString("Hello!" + rownum));// 設定單元格內容 cell.setCellStyle(cellStyle);// 設定單元格樣式 cell.setCellType(Cell.CELL_TYPE_STRING);// 指定單元格格式:數值、公式或字串 cell.setCellComment(comment);// 添加註釋 // 格式化資料 Cell cell2 = row.createCell((short) 2); cell2.setCellValue(11111.25); cell2.setCellStyle(cellStyle2); Cell cell3 = row.createCell((short) 3); cell3.setCellValue(new Date()); cell3.setCellStyle(cellStyle3); sheet.autoSizeColumn((short) 0); // 調整第一列寬度 sheet.autoSizeColumn((short) 1); // 調整第二列寬度 sheet.autoSizeColumn((short) 2); // 調整第三列寬度 sheet.autoSizeColumn((short) 3); // 調整第四列寬度 } // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(1, // 第一行(02, // last row(0-based) 1, // 第一列(基於0) // 最後一列(基於0) )); // 儲存 String filename = "C:/Users/H__D/Desktop/workbook.xls"; if (workbook instanceof XSSFWorkbook) { filename = filename + "x"; } FileOutputStream out = new FileOutputStream(filename); workbook.write(out); out.close(); } } }

使用poi修改execl檔案

package test.dzy.poi;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;



public class UpdateExcel {

    public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {

        InputStream inputStream = new FileInputStream("G:/workbook.xls");
        //InputStream inp = new FileInputStream("workbook.xlsx");

        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(2);
        Cell cell = row.getCell(3);
        if (cell == null)
            cell = row.createCell(3);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue("a test");

        // 寫操作
        FileOutputStream fileOut = new FileOutputStream("C:/Users/H__D/Desktop/workbook.xls");
        workbook.write(fileOut);
        fileOut.close();

    }

}

使用poi解析excel檔案

package test.dzy.poi;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellReference;

import com.microsoft.schemas.office.visio.x2012.main.CellType;



public class ReadExcel {

    public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {

        InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
        //InputStream inp = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");

        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);

        DataFormatter formatter = new DataFormatter();
        for (Row row : sheet) {
            for (Cell cell : row) {
                CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
                //單元格名稱
                System.out.print(cellRef.formatAsString());
                System.out.print(" - ");

                //通過獲取單元格值並應用任何資料格式(Date,0.001.23e9,$ 1.23等),獲取單元格中顯示的文字
                String text = formatter.formatCellValue(cell);
                System.out.println(text);

                 //獲取值並自己格式化
                switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:// 字串型
                        System.out.println(cell.getRichStringCellValue().getString());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:// 數值型
                        if (DateUtil.isCellDateFormatted(cell)) { // 如果是date型別則 ,獲取該cell的date值
                            System.out.println(cell.getDateCellValue());
                        } else {// 純數字
                            System.out.println(cell.getNumericCellValue());
                        }
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:// 布林
                        System.out.println(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:// 公式型
                        System.out.println(cell.getCellFormula());
                        break;
                    case Cell.CELL_TYPE_BLANK:// 空值
                        System.out.println();
                        break;
                    case Cell.CELL_TYPE_ERROR: // 故障
                        System.out.println();
                        break;
                    default:
                        System.out.println();
                }
            }
        }

    }

}