欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java讀寫(xiě)excel文件實(shí)現(xiàn)POI解析Excel的方法

 更新時(shí)間:2018年10月15日 10:36:29   作者:SimonHu1993  
在日常工作中,我們常常會(huì)進(jìn)行Excel文件讀寫(xiě)操作,這篇文章主要介紹了java讀寫(xiě)excel文件實(shí)現(xiàn)POI解析Excel的方法,實(shí)例分析了java讀寫(xiě)excel的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

在日常工作中,我們常常會(huì)進(jìn)行文件讀寫(xiě)操作,除去我們最常用的純文本文件讀寫(xiě),更多時(shí)候我們需要對(duì)Excel中的數(shù)據(jù)進(jìn)行讀取操作,本文將介紹Excel讀寫(xiě)的常用方法,希望對(duì)大家學(xué)習(xí)Java讀寫(xiě)Excel會(huì)有幫助。

package com.zhx.base.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * POI解析Excel
 */
public class ExcelReaderUtil {

  /**
   * 根據(jù)fileType不同讀取excel文件
   *
   * @param path
   * @param path
   * @throws IOException
   */
  public static List<List<String>> readExcel(String path) {
    String fileType = path.substring(path.lastIndexOf(".") + 1);
    // return a list contains many list
    List<List<String>> lists = new ArrayList<List<String>>();
    //讀取excel文件
    InputStream is = null;
    try {
      is = new FileInputStream(path);
      //獲取工作薄
      Workbook wb = null;
      if (fileType.equals("xls")) {
        wb = new HSSFWorkbook(is);
      } else if (fileType.equals("xlsx")) {
        wb = new XSSFWorkbook(is);
      } else {
        return null;
      }

      //讀取第一個(gè)工作頁(yè)sheet
      Sheet sheet = wb.getSheetAt(0);
      //第一行為標(biāo)題
      for (Row row : sheet) {
        ArrayList<String> list = new ArrayList<String>();
        for (Cell cell : row) {
          //根據(jù)不同類(lèi)型轉(zhuǎn)化成字符串
          cell.setCellType(Cell.CELL_TYPE_STRING);
          list.add(cell.getStringCellValue());
        }
        lists.add(list);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (is != null) is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return lists;
  }


  /**
   * 創(chuàng)建Excel.xls
   * @param lists 需要寫(xiě)入xls的數(shù)據(jù)
   * @param titles 列標(biāo)題
   * @param name 文件名
   * @return
   * @throws IOException
   */
  public static Workbook creatExcel(List<List<String>> lists, String[] titles, String name) throws IOException {
    System.out.println(lists);
    //創(chuàng)建新的工作薄
    Workbook wb = new HSSFWorkbook();
    // 創(chuàng)建第一個(gè)sheet(頁(yè)),并命名
    Sheet sheet = wb.createSheet(name);
    // 手動(dòng)設(shè)置列寬。第一個(gè)參數(shù)表示要為第幾列設(shè);,第二個(gè)參數(shù)表示列的寬度,n為列高的像素?cái)?shù)。
    for(int i=0;i<titles.length;i++){
      sheet.setColumnWidth((short) i, (short) (35.7 * 150));
    }

    // 創(chuàng)建第一行
    Row row = sheet.createRow((short) 0);

    // 創(chuàng)建兩種單元格格式
    CellStyle cs = wb.createCellStyle();
    CellStyle cs2 = wb.createCellStyle();

    // 創(chuàng)建兩種字體
    Font f = wb.createFont();
    Font f2 = wb.createFont();

    // 創(chuàng)建第一種字體樣式(用于列名)
    f.setFontHeightInPoints((short) 10);
    f.setColor(IndexedColors.BLACK.getIndex());
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);

    // 創(chuàng)建第二種字體樣式(用于值)
    f2.setFontHeightInPoints((short) 10);
    f2.setColor(IndexedColors.BLACK.getIndex());

    // 設(shè)置第一種單元格的樣式(用于列名)
    cs.setFont(f);
    cs.setBorderLeft(CellStyle.BORDER_THIN);
    cs.setBorderRight(CellStyle.BORDER_THIN);
    cs.setBorderTop(CellStyle.BORDER_THIN);
    cs.setBorderBottom(CellStyle.BORDER_THIN);
    cs.setAlignment(CellStyle.ALIGN_CENTER);

    // 設(shè)置第二種單元格的樣式(用于值)
    cs2.setFont(f2);
    cs2.setBorderLeft(CellStyle.BORDER_THIN);
    cs2.setBorderRight(CellStyle.BORDER_THIN);
    cs2.setBorderTop(CellStyle.BORDER_THIN);
    cs2.setBorderBottom(CellStyle.BORDER_THIN);
    cs2.setAlignment(CellStyle.ALIGN_CENTER);
    //設(shè)置列名
    for(int i=0;i<titles.length;i++){
      Cell cell = row.createCell(i);
      cell.setCellValue(titles[i]);
      cell.setCellStyle(cs);
    }
    if(lists == null || lists.size() == 0){
      return wb;
    }
    //設(shè)置每行每列的值
    for (short i = 1; i <= lists.size(); i++) {
      // Row 行,Cell 方格 , Row 和 Cell 都是從0開(kāi)始計(jì)數(shù)的
      // 創(chuàng)建一行,在頁(yè)sheet上
      Row row1 = sheet.createRow((short)i);
      for(short j=0;j<titles.length;j++){
        // 在row行上創(chuàng)建一個(gè)方格
        Cell cell = row1.createCell(j);
        cell.setCellValue(lists.get(i-1).get(j));
        cell.setCellStyle(cs2);
      }
    }
    return wb;
  }

  public static void main(String[] args) {
    String path = "d:/software/企發(fā)支付-員工信息表.xlsx";
    List<List<String>> lists = readExcel(path);
    for (List<String> list : lists) {
      for (String strs : list) {
        System.out.println(strs);
      }
    }
  }
}

需要導(dǎo)入的jar包:

 <!-- POI EXCEL 文件讀寫(xiě) -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-excelant</artifactId>
      <version>3.14</version>
    </dependency>

準(zhǔn)備需要讀寫(xiě)的文件:

上述工具類(lèi)中將每行放到一個(gè)list中,然后每行的每列放入到一個(gè)list中,這里再根據(jù)自己需求去對(duì)表中數(shù)據(jù)進(jìn)行處理:

我現(xiàn)在要取得企業(yè)名稱(chēng)(資和信***)和從第七行起開(kāi)始的id、姓名、識(shí)別號(hào)存入數(shù)據(jù)庫(kù)中,這邊我只展示service層處理,mybatis進(jìn)行批量插入:

public Map insEm(File file) throws FileNotFoundException {
    String companyName = "";
    String epid = "";
    List<Map> listMap = new ArrayList<>();
    List<List<String>> lists = ExcelReaderUtil.readExcel(file.getPath());
    for (int j = 0; j < lists.size(); j++) {
      List list = lists.get(j);
      for (int i = 0; i < list.size(); i++) {
        if (list.get(i).equals("企業(yè)名稱(chēng)")) {
          companyName = list.get(i + 1).toString();
          epid = employeeMapper.selEPID(companyName);
          break;
        } else if (list.get(i).equals("員工識(shí)別號(hào)")) {
          for (int m = j + 1; m < lists.size() - 1; m++) {
            Map map = new HashMap();
            if (null != lists.get(m) && lists.get(m).size() > 0) {
              List dataList = lists.get(m);
              map.put("id", dataList.get(0));
              map.put("epid", epid);
              map.put("name", dataList.get(1));
              map.put("identify", dataList.get(2));
              listMap.add(map);
            }
          }
        }
      }
    }
    Map dataMap = new HashMap();
    dataMap.put("employees", listMap);
    employeeMapper.insEm(dataMap);
    return null;
  }
<insert id="insEm" parameterType="java.util.Map">
    insert into qf_employee_info(epid,employee_id,user_name,phone,user_email,status,create_time,creater,create_type) value
    <foreach collection="employees" index="index" item="item" separator=",">
      (#{item.epid},"",#{item.name},#{item.identify},"",1,now(),"",2)
    </foreach>
  </insert>

最后數(shù)據(jù)庫(kù)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論