Java 使用Apache POI讀取和寫入Excel表格

1,引入所用的包java

 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.5-FINAL</version>
 </dependency>

2,建立列名List,此處將顯示到單元格每列名稱,根據本身的業務需求更改列名sql

List<String> columnList = new ArrayList();
        columnList.add("申請人帳號");
        columnList.add("申請人");
        columnList.add("提現金額");
        columnList.add("開戶行");
        columnList.add("持卡人");
        columnList.add("卡號");
        columnList.add("銀行名稱");
        columnList.add("申請時間");

3,建立將要導出的參數(實體類),此處必須和建立的列名List一一對應,不然會錯行顯示apache

package com.sanmi.active.fission.management.balance.dto;

import lombok.Data;

import java.math.BigDecimal;
import java.sql.Timestamp;

/**
 * @author:Ziggo Xu <br/>
 * <p>提現管理導出參數</p>
 * ===============================
 * Date:2018/12/12
 * Time:16:55
 * ================================
 */
@Data
public class UserBalanceCashExcelDTO {
    /**
     * 申請人帳戶
     */
    private String account;
    /**
     * 申請人
     */
    private String nickName;
    /**
     * 提現金額
     */
    private BigDecimal bcCashMoney;/**
     * 開戶行名稱
     */
    private String ubiOpenBank;
    /**
     * 持卡人姓名
     */
    private String ubiRealName;
    /**
     * 銀行卡卡號
     */
    private String ubiCardNo;
    /**
     * 銀行卡名稱
     */
    private String ubiBankName;
    /**
     * 提現時間
     */
    private Timestamp bcCreateTime;
    
}

4,建立導出Excel的工具類json

package com.sanmi.active.fission.base.util;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class Tool {
    /**
     * 導出excel操做
     * @param response
     * @param columnList 列名
     * @param list 內容
     * @param title
     * @param titlePostion 標題位置
     * @throws IllegalAccessException
     * @throws IOException
     */
    public static void export(HttpServletResponse response, List<String> columnList, List<?> list, String title, Integer titlePostion) throws IllegalAccessException, IOException {

        response.reset();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateStr = sdf.format(new Date());
        Map<String,Object> map=new HashMap<String,Object>();
        // 指定下載的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xlsx");
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        XSSFWorkbook workBook = new XSSFWorkbook();
        // 在workbook中添加一個sheet,對應Excel文件中的sheet
        XSSFSheet sheet = workBook.createSheet();

        //列號
        int colNum = 0;
        //行號
        int rowNum = 0;
        XSSFRow rowtitle = sheet.createRow(rowNum++);
        rowtitle.createCell(titlePostion).setCellValue(title);
        XSSFRow rowheader = sheet.createRow(rowNum++);
        for(String string:columnList){
            rowheader.createCell(colNum++).setCellValue(string);
        }
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            Object object = iterator.next();
            XSSFRow row = sheet.createRow(rowNum++);
            colNum=0;
            for (Field field : object.getClass().getDeclaredFields()){
                field.setAccessible(true);
                if (field.getType().isInstance(Timestamp.class)){
                    row.createCell(colNum++).setCellValue(field.get(object).toString()
                            .substring(0,field.get(object).toString().indexOf(".")));
                }else {
                    if(field.get(object) == null){
                        row.createCell(colNum++).setCellValue("");
                    }else {
                        row.createCell(colNum++).setCellValue(field.get(object).toString());
                    }
                }
            }
        }
        workBook.write(response.getOutputStream());
    }
}

5,業務邏輯處理,使用第三部建立的UserBalanceCashExcelDTO  接收集合參數 app

 List<UserBalanceCashExcelDTO> list = balanceCashApplyService.exportApplyList(param);

6,設置文檔的標題xss

   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
   String title = "提現申請導出" + "(" + df.format(new Date()) + ")";

7,調用工具類,導出文檔工具

  Tool.export(response, columnList, list, title, 1);

參考代碼以下測試

  /**
     * 導出提現信息
     *
     * @param param
     * @throws Exception
     * @throws IllegalAccessException
     */
    @RequestMapping("/exportApplyList")
    public void exportApplyList(UserBalanceCashParam param) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<UserBalanceCashExcelDTO> list = balanceCashApplyService.exportApplyList(param);
        String title = "提現申請導出" + "(" + df.format(new Date()) + ")";
        List<String> columnList = new ArrayList();
        columnList.add("申請人帳號");
        columnList.add("申請人");
        columnList.add("提現金額");
        columnList.add("開戶行");
        columnList.add("持卡人");
        columnList.add("卡號");
        columnList.add("銀行名稱");
        columnList.add("申請時間");
        //導出
        Tool.export(response, columnList, list, title, 1);
    }

導出效果圖示spa

 8,補充讀取excel邏輯實現,新建存儲實體excel

package com.sanmi.active.fission.management.balance.dto;

import lombok.Data;

import java.sql.Timestamp;

/**
 * @author:Ziggo Xu <br/>
 * <p>導出excel 實體類,與 excel列名對應</p>
 * ===============================
 * Date:2019/04/12
 * Time:16:55
 * ================================
 */
@Data
public class ExcelEntity{
    //患者id
    private String id;
    //患者名稱
    private String name;
    //患者檢查類型標識  CT MR US 病理
    private String flag;
    //患者報告內容
    private String content;
    //分析結果
    private String result;
    
}

9,補充讀取excel邏輯實現,讀取方法

    public static void begin(HttpServletResponse response) throws Exception {
        Workbook wb =null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String,String>> list = null;
        List<ExcelEntity> entitys =  new ArrayList<ExcelEntity>();
        String cellData = null;
        //這裏設置要讀取的原始數據
        String filePath = "D:\\濰坊二院數據.xls";
        //此處的數據是沒有意義的,只是爲了讀取原始數據的列數(5列),設置失誤會致使缺失數據
        String columns[] = {"id","name","flag","flagName","content"};
        wb = readExcel(filePath);
        if(wb != null){
            //用來存放表中數據
            list = new ArrayList<Map<String,String>>();
            //獲取第三個sheet
            sheet = wb.getSheetAt(2);
            //獲取最大行數
            int rownum = sheet.getPhysicalNumberOfRows();
            //獲取第一行
            row = sheet.getRow(0);
            //獲取最大列數
           // int colnum = row.getPhysicalNumberOfCells();
            int colnum = 5;//暫定數據,最大五行,其餘空白行無心義
            
            ExcelEntity entity = new ExcelEntity();
            for (int i = 1; i<rownum; i++) {
                Map<String,String> map = new LinkedHashMap<String,String>();
                row = sheet.getRow(i);
                     if(row !=null){
                         for (int j=0;j<colnum;j++){
                             cellData = (String) getCellFormatValue(row.getCell(j));
                             map.put(columns[j], cellData);
                         }
                     }else{
                         break;
                     }    
                list.add(map);
                     //entitys.add(entity);
            }
        }
        //遍歷解析出來的list
        for (Map<String,String> map : list) {
            String flag = null;
            String content;
            JSONArray jsonArry = null;
            String id = null;
            ExcelEntity entity = new ExcelEntity();
            for (Entry<String,String> entry : map.entrySet()) {
               // System.out.print(entry.getKey()+":"+entry.getValue()+",");
                //檢查類型
                if(entry.getKey().equals("flag")) {
                     flag = entry.getValue();
                     entity.setFlag(entry.getValue());
                }
                //檢查的內容
                if(entry.getKey().equals("content")) {
                    content = entry.getValue();
                    content = "[{'content':'"+content+"','pat_in_hos_id':'"+id+"','study_bodypart':'test','time':'2019-03-01 12:05:00'}]";
                    if(!EmptyUtil.isEmpty(content)) {
                     jsonArry =JSONArray.fromObject(content);
                    } 
                    entity.setContent(content);
                    }             
                //檢查患者的Id
                if(entry.getKey().equals("id")) {   
                    id = entry.getValue();
                    entity.setId(id);
                }
                //檢查患者的名稱
                if(entry.getKey().equals("name")) {  
                    entity.setName(entry.getValue());
                }
            }
            entity.setResult("測試結果");
            entitys.add(entity);           
        }  
        //讀取方法完成,已封裝爲list實體!!!!!!
        System.out.println(entitys.size());
    }
相關文章
相關標籤/搜索