Java POI Excel 導入導出

這個東西很容易懂,不是特別難,難就難在一些複雜的計算和Excel格式的調整上。java

近期寫了一個小列子,放上來便於之後使用。apache

POI.jar下載地址:http://mirror.bit.edu.cn/apache/poi/release/bin/poi-bin-3.17-20170915.zipide

Entity 實體類字體

package com.test2;

import java.util.Date;

public class User {

    private int id; 
    private String username;
    private String password;
    private String sex;
    private int age;
    private Date birth;
    
    public int getId() {
        return id;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public String getSex() {
        return sex;
    }
    public int getAge() {
        return age;
    }
    public Date getBirth() {
        return birth;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", sex=" + sex + ", age=" + age
                + ", birth=" + birth + "]";
    }
    
    public User() {};
    public User(int id, String username, String password, String sex, int age, Date birth) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.age = age;
        this.birth = birth;
    }
   
}

 

 

Excel 導出:this

package com.test2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExportExcel {
    
    public static void main(String[] args) {
        try {
            // 建立一個工做簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 5);
            HSSFCellStyle headStyle = getStyle(workbook,(short) 15);
            HSSFCellStyle colStyle = getStyle(workbook,(short) 12);
            
            //新建一個excel頁籤
            HSSFSheet createSheet = workbook.createSheet("用戶信息列表");
            // 將合併表格的對象添加頁籤中
            createSheet.addMergedRegion(cellRangeAddress);
            // 設置單元格的默認寬度
            createSheet.setDefaultColumnWidth(25);
            
            // 建立一行
            HSSFRow row0 = createSheet.createRow(0);
            HSSFCell cell0 = row0.createCell(0);
            // 添加標題樣式
            cell0.setCellStyle(headStyle);
            // 添加標題
            cell0.setCellValue("用戶信息列表");
            
            //設置列的標題
            String [] titles = {"id","用戶名","密碼","年齡","性別","生日"};
            HSSFRow row1 = createSheet.createRow(1);
            //  循環往excel中添加列標題
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell1 = row1.createCell(i);
                cell1.setCellStyle(colStyle);
                cell1.setCellValue(titles[i]);
            }
            
            List<User> userList = new ArrayList<User>();
            
            userList.add(new User(1,"zhangsan1","123","男",21,new Date()));
            userList.add(new User(2,"zhangsan2","456","男",21,new Date()));
            userList.add(new User(3,"zhangsan3","789","女",21,new Date()));
            userList.add(new User(4,"zhangsan4","000","男",21,new Date()));
            
            for (int i = 0; i < userList.size(); i++) {
                //建立第三行
                HSSFRow row2 = createSheet.createRow(i + 2);
                
                HSSFCell cell_0 = row2.createCell(0);
                cell_0.setCellValue(userList.get(i).getId());
                
                
                HSSFCell cell_1 = row2.createCell(1);
                cell_1.setCellValue(userList.get(i).getUsername());
                
                
                HSSFCell cell_2 = row2.createCell(2);
                cell_2.setCellValue(userList.get(i).getPassword());
                
                HSSFCell cell_3 = row2.createCell(3);
                cell_3.setCellValue(userList.get(i).getAge());
                
                HSSFCell cell_4 = row2.createCell(4);
                cell_4.setCellValue(userList.get(i).getSex());
                
                
                HSSFCell cell_5 = row2.createCell(5);
                cell_5.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(userList.get(i).getBirth()));
                
            }
            
            OutputStream os = new FileOutputStream("E:/test.xls");
            workbook.write(os);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook,short fontSize) {
        // 建立樣式對象
        HSSFCellStyle createCellStyle = workbook.createCellStyle();
        //水平居中
        createCellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        createCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 設置邊框
        createCellStyle.setBorderBottom(BorderStyle.THIN);
        createCellStyle.setBorderLeft(BorderStyle.THIN);
        createCellStyle.setBorderRight(BorderStyle.THIN);
        createCellStyle.setBorderTop(BorderStyle.THIN);
        
        //  建立一個字體對象
        HSSFFont createFont = workbook.createFont();
        // 設置字體的大小
        createFont.setFontHeightInPoints(fontSize);
        // 設置字體類型
        createFont.setFontName("微軟雅黑");
        // 設置字體的顏色
        createFont.setColor(HSSFColor.RED.index);
        
        //將字體放置到樣式中
        createCellStyle.setFont(createFont);
        return createCellStyle;
    }
    
}

如下是導出Excel的結果圖:spa

 

這裏補充下合併單元格的知識點:excel

/*合併單元格須要用到CellRangeAddress對象 
CellRangeAddress對象須要傳入四個參數 列如:CellRangeAddress(param1,param2,param3,param4);
參數分別表明以下:
param1:開始行 
param2:結束行  
param3:開始列 
param4:結束列  
例如:
合併第一行和第二行,此合併只是合併了第一列,第二列、第三列...等後面的列的一二行並無合併
給合併的單元格賦值是須要注意行號變化
注意:記住行號和列號是從0起始
*/
sheet.addMergedRegion(new CellRangeAddress(0,1,0,0));  

下面粘貼一段合併單元格行和列的綜合代碼:code

public static void main(String[] args) {
    try {
        // 建立標題欄
        String[] titles = new String[] {"公司名稱","項目名稱","地址名稱"};
        String[] strDate = new String[] {"2018-04-29","2018-04-30","2018-05-01","2018-05-02","2018-05-03"};
        
        // 建立一個工做簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //拿到標題樣式和單元格樣式
        HSSFCellStyle headStyle = getStyle(workbook,(short) 15);
        HSSFCellStyle colStyle = getStyle(workbook,(short) 12);
        
        //新建一個excel頁籤
        HSSFSheet createSheet = workbook.createSheet("地址信息報表");
        // 將合併表格的對象添加頁籤中
        CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, (6+strDate.length));
        createSheet.addMergedRegion(cellRangeAddress);
        //循環合併1至3列的的一二行
        for (int i = 0; i < 3; i++) {
            createSheet.addMergedRegion(new CellRangeAddress(1, 2, i, i));
        }
        createSheet.addMergedRegion(new CellRangeAddress(1, 1, 3, 3+strDate.length));
        // 設置單元格的默認寬度
        createSheet.setDefaultColumnWidth(25);
        
        // 建立一行
        HSSFRow row0 = createSheet.createRow(0);
        HSSFCell cell0 = row0.createCell(0);
        // 添加標題樣式
        cell0.setCellStyle(headStyle);
        // 添加標題
        cell0.setCellValue("地址信息報表");
        
        //設置列的標題
        HSSFRow row1 = createSheet.createRow(1);
        //  循環往excel中添加列標題
        for (int i = 0; i < titles.length; i++) {
            HSSFCell cell1 = row1.createCell(i);
            cell1.setCellStyle(colStyle);
            cell1.setCellValue(titles[i]);
        }
        HSSFCell dateCell = row1.createCell(titles.length);
        dateCell.setCellStyle(colStyle);
        dateCell.setCellValue("2018-04-29 / 2018-05-03");
        
        HSSFRow row2 = createSheet.createRow(2);
        //  循環往excel中添加列標題
        for (int i = 0; i < strDate.length; i++) {
            HSSFCell cell1 = row2.createCell(i + titles.length);
            cell1.setCellStyle(colStyle);
            cell1.setCellValue(strDate[i]);
        }
        
        OutputStream os = new FileOutputStream("E:/test.xls");
        workbook.write(os);
        os.close();
    } catch (Exception e){
        e.printStackTrace();
    }
    
    
}

結果以下:orm

 

 

Excel導入:對象

package com.test2;

import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 
 * @author zhangxiang
 *
 */
public class ImportExcel {

    public static void main(String[] args) {
        
        try {
            //建立輸入流對象
            InputStream inputStream = new FileInputStream("E:/test.xls");
            // 建立工做波對象
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            // 建立user集合對象用於存儲Excel導入的信息
            List<User> userList = new ArrayList<User>();
            
            
            //  是否能拿到excel頁籤
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                
                HSSFSheet sheetAt = workbook.getSheetAt(i);
                //  不存在就結束循環
                if(null == sheetAt) {
                    continue;
                }
                
                //  是否存在row
                for (int j = 0; j < sheetAt.getPhysicalNumberOfRows(); j++) {
                    
                    // 拿到第 j+2 行  前兩行是標題 
                    HSSFRow row = sheetAt.getRow(2+j); 
                    // 不存在row就結束循環
                    if(null == row) {
                        continue;
                    }
                    
                    // 存儲一行的每一個單元格拿到的值
                    User user = new User();
                    
                    // 拿到第一個單元格的值   單元格從0開始
                    HSSFCell cell0 = row.getCell(0);
                    Float f = Float.parseFloat(cell0.toString());
                    user.setId(f.intValue());
                    
                    // 第二個單元格的值
                    HSSFCell cell1 = row.getCell(1);
                    user.setUsername(cell1.toString());
                    
                    //第三個
                    HSSFCell cell2 = row.getCell(2);
                    user.setPassword(cell2.toString());
                    
                    //第四個
                    HSSFCell cell3 = row.getCell(3);
                    Float a = Float.parseFloat(cell3.toString());
                    user.setAge(a.intValue());
                    
                    // 第五個
                    HSSFCell cell4 = row.getCell(4);
                    user.setSex(cell4.toString());
                    
                    //第六個
                    HSSFCell cell5 = row.getCell(5);
                    user.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse(cell5.toString()));
                    
                    
                    userList.add(user);
                }
            }
            //  輸出信息  查看是否正確
            System.out.println(userList.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    
}

 如下是導入Excel 的部分打印結果圖:

 

以上代碼直接就能夠運行!!

相關文章
相關標籤/搜索