JXL讀寫Excel表格數據

工做中經常須要將查詢或者計算的結果導出到excel中,方便統計和查看,或者從excel中讀取內容。除了原來使用的poi,還有一種輕量高效的方法就是使用jxl,下面看看jxl的使用。java

導入依賴:

<!-- https://mvnrepository.com/artifact/jexcelapi/jxl -->
        <dependency>
            <groupId>jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>

Show Code

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import java.io.File;

public class TestJxl {
    public static void main(String[] args) throws Exception{
        //寫excel
        writeExcel();

        //讀excel
        //readExcel();
    }

    /**
     * 寫數據到excel中
     *
     * @throws Exception
     */
    private static void writeExcel() throws Exception {

        File xlsFile = new File("test.xls");
        // 建立一個工做簿
        WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
        // 建立一個工做表
        WritableSheet sheet = workbook.createSheet("sheet1", 0);
        // 向行和列中寫數據
        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 10; col++) {
                // 向工做表中添加數據
                sheet.addCell(new Label(col, row, "data[" + row + ":" + col + "]"));
            }
        }
        //關閉資源
        workbook.write();
        workbook.close();
    }

    /**
     * 從excel中讀取數據
     * @throws Exception
     */
    private static void readExcel() throws Exception {
        File xlsFile = new File("test.xls");
        // 得到工做簿對象
        Workbook workbook = Workbook.getWorkbook(xlsFile);
        // 得到全部工做表
        Sheet[] sheets = workbook.getSheets();
        // 遍歷工做表
        if (sheets != null) {
            for (Sheet sheet : sheets) {
                // 得到行數
                int rows = sheet.getRows();
                // 得到列數
                int cols = sheet.getColumns();
                // 讀取數據
                for (int row = 0; row < rows; row++) {
                    for (int col = 0; col < cols; col++) {
                        Cell cell = sheet.getCell(col, row);
                        System.out.print(cell.getContents() + " ");
                    }
                    System.out.println();
                }
            }
        }
        //關閉資源
        workbook.close();
    }
}

寫入效果

JXL讀寫Excel表格數據

讀取效果

JXL讀寫Excel表格數據

相關文章
相關標籤/搜索