1. 程式人生 > >java Workbook 讀寫excel

java Workbook 讀寫excel

1. 讀取具體位置的excel資料

 

package com.royan.weakey.platform.common.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * read a excel file of the definite path */ @Slf4j public class ReadExcel<T> { public static void main(String[] args) { ReadExcel<String> obj = new ReadExcel<>(); File file
= new File("path"); List<List<List>> excelList = obj.readExcel(file); excelList.forEach(sheet -> { sheet.forEach(row -> { row.forEach(column -> { System.out.print(column + " "); }); System.out.println(); }); }); }
public List<List<List>> readExcel(File file) { try { //create input stream ,get data InputStream stream = new FileInputStream(file); Workbook wb = new HSSFWorkbook(stream); int sheetSize = wb.getNumberOfSheets(); List<List<List>> sheetList = new ArrayList<>(); for (int i = 0; i < sheetSize; i++) { List<List> outerList = new ArrayList<>(); Sheet sheet = wb.getSheetAt(i); for (int j = 0; j <= sheet.getLastRowNum(); j++) { List<String> list = new ArrayList<>(); for (int c = 0; c < sheet.getRow(j).getLastCellNum(); c++) { Cell cell = sheet.getRow(j).getCell(c); String str = cell.getStringCellValue(); list.add(str); } outerList.add(list); } sheetList.add(outerList); } return sheetList; } catch (Exception e) { log.info(e.getMessage()); } return null; } }

 

 

 

 

2.將資料寫入指定的位置的excel

 

 

 

package com.royan.weakey.platform.common.excel;

import com.google.common.collect.Lists;
import com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.*;

/**
 * writeExcel
 */
@Slf4j
public class WriteExcel {
    private static final String EXEL_XLS = "xls";
    private static final String EXEL_XLSX = "xlsx";


    public static void writeExcel(List<Map> dataList, String filePath, List<String> header) {
        OutputStream out = null;
        try {

            /**
             read  excel document
             */
            File file = new File(filePath);
            Workbook workbook = null;
            if (file.isDirectory()) {
                // default create .xls
                workbook = new HSSFWorkbook();
            } else if (file.getName().endsWith(".xls")) {
                workbook = new HSSFWorkbook();
            } else if (file.getName().endsWith(".xlsx")) {
                workbook = new XSSFWorkbook();
            } else
                throw new Exception("please get  .xls .xlsx end or directory,[" + filePath + "]");
            //if only support  single sheet
            Sheet sheet = workbook.createSheet("data");
            //set excel header
            Row fisrtRow = sheet.createRow(0);
            int columnCount = header.size();
            for (int h = 0; h < columnCount; h++) {
                fisrtRow.createCell(h).setCellValue(header.get(h));
            }
            /**
             * fill up  data in excel
             */
            int i = 1;
            for (Map data : dataList) {
                Row row = sheet.createRow(i);
                Object[] arrays = data.values().toArray();
                for (int j = 0; j < columnCount; j++) {
                    Object obj = arrays[j];
                    row.createCell(j).setCellValue(obj != null ? obj.toString() : "");
                }
                i++;
            }
            out = new FileOutputStream(file.isDirectory() ? filePath + "/" + header.get(0) + ".xls" : filePath);
            workbook.write(out);

        } catch (Exception e) {
            log.info("exception {}", e);
        } finally {

            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException o) {
                log.info("exception {}", o);
            }
            log.info("data output success");
        }


    }


    public static void main(String[] args) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("BankName", "BankName");
        dataMap.put("Addr", "Addr");
        dataMap.put("Phone", "Phone");
        Map<String, Object> dataMap1 = new HashMap<>();
        dataMap1.put("BankName", "BankName1");
        dataMap1.put("Addr", "Addr1");
        dataMap1.put("Phone", "Phone1");
        List<String> header = new LinkedList<>();
        header.add("BankName");
        header.add("Addr");
        header.add("Phone");
        List<Map> list = new ArrayList<>();
        list.add(dataMap);
        list.add(dataMap1);
        writeExcel(list, "/Users/caibixiang/workSoftware/log", header);

    }

}