首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 讀寫 Excel 完整教程:基於 JExcelApi (jxl) 的實戰代碼

     編輯:Java 相關知識

JExcelApi 簡介

JExcelApi (jxl) 是開源 Java Excel 庫,支援 .xls (Excel 95-2003) 格式。主要特性:

  • 讀寫工作表、單元格、公式(Excel 97+)
  • 字體、數字/日期格式、邊框、背景色、圖表/圖片複製
  • 修改現有工作簿、國際化公式、Log4j/JCL 日誌整合

下載:jexcelapi.sourceforge.net,將 jxl.jar 加入 Classpath。


一、寫入 Excel 完整示例

package writer;
import java.io.File; import java.io.IOException; import java.util.Locale;
import jxl.*; import jxl.format.UnderlineStyle;
import jxl.write.*;

public class WriteExcel {
    private WritableCellFormat timesBoldUnderline, times;
    private String outputFile;

    public void setOutputFile(String file) { this.outputFile = file; }

    public void write() throws IOException, WriteException {
        File file = new File(outputFile);
        WorkbookSettings ws = new WorkbookSettings();
        ws.setLocale(new Locale("en", "EN"));

        WritableWorkbook workbook = Workbook.createWorkbook(file, ws);
        WritableSheet sheet = workbook.createSheet("Report", 0);

        createLabel(sheet);   // 表頭
        createContent(sheet); // 數據

        workbook.write();
        workbook.close();
    }

    private void createLabel(WritableSheet sheet) throws WriteException {
        WritableFont font10 = new WritableFont(WritableFont.TIMES, 10);
        times = new WritableCellFormat(font10);
        times.setWrap(true);

        WritableFont boldFont = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
        timesBoldUnderline = new WritableCellFormat(boldFont);
        timesBoldUnderline.setWrap(true);

        CellView cv = new CellView();
        cv.setFormat(times); cv.setFormat(timesBoldUnderline); cv.setAutosize(true);

        addCaption(sheet, 0, 0, "Header 1");
        addCaption(sheet, 1, 0, "Another Header");
    }

    private void createContent(WritableSheet sheet) throws WriteException, RowsExceededException {
        // 數字與公式
        for (int i = 1; i < 10; i++) {
            addNumber(sheet, 0, i, i + 10);      // A 列
            addNumber(sheet, 1, i, i * i);       // B 列
        }
        // SUM 公式
        sheet.addCell(new Formula(0, 10, "SUM(A2:A10)"));
        sheet.addCell(new Formula(1, 10, "SUM(B2:B10)"));

        // 文字
        for (int i = 12; i < 20; i++) {
            addLabel(sheet, 0, i, "Text " + i);
            addLabel(sheet, 1, i, "More Text");
        }
    }

    private void addCaption(WritableSheet s, int col, int row, String txt) throws WriteException, RowsExceededException {
        s.addCell(new Label(col, row, txt, timesBoldUnderline));
    }
    private void addNumber(WritableSheet s, int col, int row, Integer val) throws WriteException, RowsExceededException {
        s.addCell(new Number(col, row, val, times));
    }
    private void addLabel(WritableSheet s, int col, int row, String txt) throws WriteException, RowsExceededException {
        s.addCell(new Label(col, row, txt, times));
    }

    public static void main(String[] args) throws Exception {
        WriteExcel test = new WriteExcel();
        test.setOutputFile("c:/temp/report.xls");
        test.write();
        System.out.println("File generated: c:/temp/report.xls");
    }
}

二、讀取 Excel 完整示例

package reader;
import java.io.File; import java.io.IOException;
import jxl.*; import jxl.read.biff.BiffException;

public class ReadExcel {
    private String inputFile;

    public void setInputFile(String file) { this.inputFile = file; }

    public void read() throws IOException, BiffException {
        Workbook wb = Workbook.getWorkbook(new File(inputFile));
        Sheet sheet = wb.getSheet(0); // 第一張表

        for (int col = 0; col < sheet.getColumns(); col++) {
            for (int row = 0; row < sheet.getRows(); row++) {
                Cell cell = sheet.getCell(col, row);
                if (cell.getType() == CellType.LABEL) {
                    System.out.println("Label: " + cell.getContents());
                } else if (cell.getType() == CellType.NUMBER) {
                    System.out.println("Number: " + cell.getContents());
                }
                // 可擴展:CellType.FORMULA, BOOLEAN, DATE 等
            }
        }
        wb.close();
    }

    public static void main(String[] args) throws Exception {
        ReadExcel test = new ReadExcel();
        test.setInputFile("c:/temp/report.xls");
        test.read();
    }
}

遷移提示:JExcelApi 已停更,新專案建議用 Apache POI

場景推薦庫理由
新專案、.xlsx 支援Apache POI (XSSF)活躍維護、支援 .xls/.xlsx、功能全面
舊系統維護、僅 .xlsJExcelApi (jxl)輕量、API 簡單、現有代碼兼容
大數據量流式讀寫POI SAX (XSSFReader) / EasyExcel低記憶體佔用、高效能

本文代碼基於 JExcelApi 經典用法,適合維護舊專案或快速原型。新專案請直接採用 Apache POI 或阿里 EasyExcel。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved