JAVA讀取、寫入Excel表格(含03版)


引言

工作中可能會遇到對Excel讀取和寫入,如果我們自己手動寫的話,會很麻煩,但是Apache中有poi工具類。poi工具類封裝好了對於Excel讀取和寫入,我們需要用的時候,直接調用該方法就好了。
注:03和07的寫法不一致。
區別如下

        // HSSFWorkbook 2003的excel .xls,XSSFWorkbook導入2007的excel   .xlsx
        HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(file)));
        XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(new File(file))));

代碼實現

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONObject;



/** * * Title: excelTest * Description: excel表格讀取 * 注意:引用poi 架包版本要一致 * 如: * poi-3.13.jar * poi-ooxml-3.13.jar * poi-ooxml-schemas-3.13.jar * poi-scratchpad-3.13.jar * 這些架包版本隨意 * stax-api.jar * xmlbeans.jar * dom4j.jar * Version:1.0.0 * @author pancm */
public class excelTest {

    private static final String path="D:\\file\\test.xlsx"; 
    private static final String path1="D:\\file\\test1.xlsx"; 

    public static void main(String[] args) throws FileNotFoundException, IOException {
        readExcel(path);
        writeExcel(path1);
    }

    /** * 讀取Excel表格內容 * @throws FileNotFoundException * @throws IOException */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static void readExcel(String str) throws FileNotFoundException, IOException{
        File file=new File(str);
        // HSSFWorkbook 2003的excel .xls,XSSFWorkbook導入2007的excel .xlsx
// HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(file)));
        XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(file));
         Sheet sheet=workbook.getSheetAt(0);//讀取第一個 sheet
         List list= new ArrayList<>();
         Row row=null;
         int count=sheet.getPhysicalNumberOfRows();
        //逐行處理 excel 數據
        for (int i = 1; i <count; i++) {
             JSONObject json=new JSONObject();
              row=sheet.getRow(i);
             Cell cell0 = row.getCell(0);
             //設置取值為String
             //整數數據要轉,否則會變成浮點數
            cell0.setCellType(Cell.CELL_TYPE_STRING);
            Cell cell1 = row.getCell(1); 
            cell1.setCellType(Cell.CELL_TYPE_STRING);
            json.put("Id",cell0.toString()); //編號
            json.put("Name",cell1.toString()); //名稱
            list.add(json);
            System.out.println("json:"+json);
        }
        workbook.close();
        System.out.println("list:"+list);
    }

    /** * 寫入Excel表格內容 * @throws FileNotFoundException * @throws IOException */
    @SuppressWarnings({ "resource", "rawtypes", "unchecked" })
    private static void writeExcel(String str) throws FileNotFoundException, IOException{
        File file=new File(str);
        // HSSFWorkbook 2003的excel .xls,XSSFWorkbook導入2007的excel .xlsx
// HSSFWorkbook workbook=new HSSFWorkbook(new FileInputStream(new File(file)));
        XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(file));
        List resultList =new ArrayList<>();

        Sheet sheet1 = workbook.createSheet();//創建 sheet 對象
        Row row = sheet1.createRow(0);//第一行,標題
        row.createCell(0).setCellValue("A");
        row.createCell(1).setCellValue("B");
        row.createCell(2).setCellValue("C");
        row.createCell(3).setCellValue("D");
        row.createCell(4).setCellValue("E");
        //拼接數據
        for(int i=1;i<=10;i++){
            JSONObject json1=new JSONObject();
            json1.put("A", i);
            json1.put("B", i*2);
            json1.put("C", i*3);
            json1.put("D", i*4);
            json1.put("E", i*5);
            resultList.add(json1);
        }
        System.out.println("resultList:"+resultList);
        Row row1;
        for (int i = 1, len = resultList.size(); i <=len; i++) {//循環創建數據行
            //因為第一行已經設置了,所以從第二行開始
            row1 = sheet1.createRow(i);
            JSONObject json=(JSONObject) resultList.get(i-1);
            row1.createCell(0).setCellValue(json.getString("A"));
            row1.createCell(1).setCellValue(json.getString("B"));
            row1.createCell(2).setCellValue(json.getString("C"));
            row1.createCell(3).setCellValue(json.getString("D"));
            row1.createCell(4).setCellValue(json.getString("E"));
        }
        FileOutputStream fos = new FileOutputStream(path1); 
        workbook.write(fos);//寫文件
        fos.close();
        System.out.println("寫入成功!");
    }
}

示例圖

讀取Excel

新建一個Excel表格,設置表格內容。
這里寫圖片描述

關閉此Excel,運行代碼,打印獲取的數據。
這里寫圖片描述

寫入Excel

創建一個新的Excel。
這里寫圖片描述

關閉此Excel,運行代碼
這里寫圖片描述

再次打開此Excel
這里寫圖片描述


免責聲明!

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



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