天天看點

Java使用POI對excel得操作

Java使用POI對excel得操作

我們這裡隻支援 03 和 07 得 檔案字尾.xlsx

引入我們需要得坐标(普通得mevan項目)

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

           

簡單輸出Excel

package com.itheima.test;


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * HSSFWorkbook :操作excel03版本的poi對象
 * XSSFWorkbook :操作excel07版本及以後的poi對象
 * SXSSFWorkbook:百萬級資料POI使用的對象
 */
public class test01 {
    public static void main(String[] args) throws Exception {
        //1.建立excel對象   ---> excel檔案
        XSSFWorkbook wb = new XSSFWorkbook();
        //2.建立sheet對象   ---->excel檔案中得 表格 sheet
        Sheet sheet = wb.createSheet();
        //3.建立行對象 (指定位置得行 row) 索引從0開始
        Row row = sheet.createRow(1);  //-->XSSFRow row = sheet.createRow(1)
        //4.建立單元格對象 (指定位置的單元格) 索引從0開始
        Cell cell = row.createCell(1);
        //5.設定單元格内容 及 樣式
        cell.setCellValue("哈哈");
        //建立樣式對象
        XSSFCellStyle cellStyle = wb.createCellStyle();
        //建立字型對象  字型樣式
        Font font = wb.createFont(); //建立字型對象
        font.setFontName("微軟雅黑"); //設定字型
        font.setBold(true); //字型加粗
        font.setFontHeightInPoints((short)48);//設定字型大小
        font.setColor((short)10);  //設定字型顔色 紅色  --->font.setColor (Font.COLOR_RED)
        cellStyle.setFont(font); // 給樣式對象添加字型特征
        cell.setCellStyle(cellStyle); //添加單元格樣式
        //6.把excle的記憶體對象生成檔案  此處會出現異常 2種異常
//        FileOutputStream os = new FileOutputStream("C:\Users\wuxin\Desktop\test001.xlsx");  //輸出到的位置
        OutputStream os = new FileOutputStream("C:\\Users\\wuxin\\Desktop\\test001.xlsx");
        wb.write(os);  //輸出 檔案下載下傳
        //7.關閉資源 記憶體
        os.close();  //關閉流
        wb.close();  //關閉excel記憶體對象
    }
}

           

擷取模闆 入門

package com.itheima.test;


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class test02 {
    public static void main(String[] args) throws Exception {
        //1.建立excel對象,利用有參構造 擷取模闆對象   //會有找不到的流的異常 //讀取的是模闆檔案
        XSSFWorkbook wb = new XSSFWorkbook("C:\\Users\\wuxin\\Desktop\\a.xlsx");
        //2.讀取excel模闆對象  根據索引  0 開始
        Sheet sheet = wb.getSheetAt(0);
        //3.讀取行
        Row row = sheet.getRow(0);
        //4.讀取單元格
        Cell cell = row.getCell(0);
        //5.擷取cell單元格樣式
        CellStyle cellStyle = cell.getCellStyle();
        //6.擷取單元格内容
        String stringCellValue = cell.getStringCellValue();
        System.out.println(cellStyle); //列印樣式對象
        System.out.println(stringCellValue); //列印單元格内容
        wb.close();
    }
}
           

##上傳

@RequestMapping("/import")
    public String imports(String contractId ,MultipartFile file) throws IOException {
        //使用file 擷取字流
        InputStream in = file.getInputStream();
        //使用位元組輸入流建構一個EXcel對象
        XSSFWorkbook wb = new XSSFWorkbook(in);
        //擷取需要的表格
        XSSFSheet sheet = wb.getSheetAt(0);
        //擷取全部的行  疊代器  不确定有多少行
        // int  last = sheet.getLastRowNum(); 擷取row總數
        Iterator<Row> iterator = sheet.iterator();
        int index = 0 ;
        Object[] box = new Object[10];
        //貨物對象集合
        List<ContractProduct> list = new ArrayList();
        while (iterator.hasNext()){
            Row next = iterator.next();
            if(index == 0){ //不要标題頭  第一次結束目前循環
                index++;
                continue;
            }
            //擷取目前行的中的沒有單元格的文字内容
            for (int i = 1; i < 10; i++) {
                //這裡取出的都是字元串  不是我們想要的 我們定義個方法 處理一下
                box[i] = getValue( next.getCell(i));
            }
            ContractProduct cp = new ContractProduct(box,super.companyId,super.companyName);
            cp.setContractId(contractId);
            list.add(cp);
        }
        //list中存這全部的資料  調用service 實作儲存
        contractProductService.BatchSave(list);
        return "redirect:/cargo/contract/list.do";
    }

    private Object getValue(Cell cell ) {
        //定義一個傳回值
        Object rtValue = null ;
        CellType cellType = cell.getCellType(); //擷取cell中内容類型
        switch (cellType){
            case STRING : //字元串
                rtValue = cell.getStringCellValue() ;
                break;
            case NUMERIC : //日期 和 數字都是這個類型
                if(DateUtil.isCellDateFormatted(cell)){
                    rtValue = cell.getDateCellValue() ;
                }else{ //全看作double
                    rtValue = cell.getNumericCellValue() ;
                }
                break;
            case BOOLEAN : //布爾類型
                rtValue = cell.getBooleanCellValue() ;
                break;
                default:
                    return null;
        }
        return rtValue;
    }