Java解析,導出Excel文件(.xlsx跟.xls兩種格式)&字體修改&單元格合並


做項目時要用到Excel批量導入導出數據,網上搜了以下大部分都是.xls格式Excel文件的教程。

導入.xlsx跟.xls格式的過程差不了多少,就是導出的時候好像有點不同,而且網上也沒教程,於是硬着頭皮寫了一個(並沒有看官方Api文檔( ̄▽ ̄)")。

首先是導入Jar包,在上傳的項目里面已經將需要用到的Jar文件放在lib文件夾里面了,我們只需要在Eclipse里面設置一下:

這里表格信息用Teacher這個類封裝:

package JavaBean;

public class Teacher {
    private String Email;
    private String Name;
    private String Password;
    private String Major;
    public Teacher(String Email,String Password,String Name,String Major) {
        this.Email=Email;
        this.Password=Password;
        this.Name=Name;
        this.Major=Major;
    }
    public String getEmail() {
        return Email;
    }
    public String getName() {
        return Name;
    }
    public String getPassword() {
        return Password;
    }
    public String getMajor() {
        return Major;
    }
    public String toString() {
        String information=String.format("Email:%s  Major:%s  Name:%s  Password:%s", this.Email,this.Major,this.Name,this.Password);
        return information;
    }
}

字體設置的類:(由於表格的每個格子都需要設置一下,單獨建個類方便些)

package Excel;

import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/*
 * 該類用於對表格主題樣式的設置
 */
public class Style {
    public static XSSFCellStyle createCellStyle(XSSFWorkbook workbook){
        XSSFFont font=workbook.createFont();
        //在對應的workbook中新建字體
        font.setFontName("微軟雅黑");
        //字體微軟雅黑
        font.setFontHeightInPoints((short)11);
        //設置字體大小
        XSSFCellStyle style=workbook.createCellStyle();
        //新建Cell字體
        style.setFont(font);
        return style;
    }
}

最后是導入導出:

package Excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



import JavaBean.Teacher;
/**
 * 
 * 該類用於教師於學生對應關系表格的讀取.xlsx和輸出.xlsx表格文件,同時也支持xls格式的Excel表格文件
 * 參考https://www.cnblogs.com/hhhshct/p/7255915.html
 */
public class TeacherTableEnhanced {
    private String filePath;//文件位置
    private final String outPutSheetName="學生預約系統教師信息";//Excel文件的標題
    public TeacherTableEnhanced(String filePath){//構造方法,Excel文件位置為參數
        this.filePath=filePath;
    }
    public List<Teacher> getFromExcel(){
        List<Teacher> teachers=null;
        try{
            Workbook wb =null;
            Sheet sheet = null;
            Row row = null;
            teachers =new ArrayList<Teacher>();
            wb = readExcel(filePath);//指定Excel對象
            if(wb != null){        
                //獲取第一個表
                sheet = wb.getSheetAt(0);
                //獲取最大行數
                int rownum = sheet.getPhysicalNumberOfRows();
                //獲取最大列數
                String Email,Major,Name,Password;
                for (int i = 2; i<rownum; i++) {//這里從第三行開始讀取數據
                    row = sheet.getRow(i);//獲得制定行數
                    Cell cell0=row.getCell(0);//分別從每個格子中獲取內容
                    Cell cell1=row.getCell(1);
                    Cell cell2=row.getCell(2);
                    Cell cell3=row.getCell(3);
                    cell0.setCellType(Cell.CELL_TYPE_STRING);
                    cell1.setCellType(Cell.CELL_TYPE_STRING);
                    cell2.setCellType(Cell.CELL_TYPE_STRING);
                    cell3.setCellType(Cell.CELL_TYPE_STRING);
                    //設置Excel內容為文本類型    ,不加執行不了
                    Email=cell0.toString();
                    Major=cell1.toString();
                    Name=cell2.toString();
                    Password=cell3.toString();//toString獲得內容
                    teachers.add(new Teacher(Email, Password, Name, Major));
                }
            }
            
        }catch (Exception e) {
            System.out.print("文件格式不正確!");
            e.printStackTrace();
        }
        return teachers;
    }
    //讀取excel
    public Workbook readExcel(String filePath){
         Workbook wb = null;
         if(filePath==null){
             return null;
         }
         String extString = filePath.substring(filePath.lastIndexOf("."));//獲取文件格式
         InputStream is = null;
         try {
             is = new FileInputStream(filePath);
             if(".xls".equals(extString)){//判斷Excel文件格式
                 return wb = new HSSFWorkbook(is);
             }else if(".xlsx".equals(extString)){
                 return wb = new XSSFWorkbook(is);
             }else{
                 return wb = null;
             }
         } catch (FileNotFoundException e) {
                e.printStackTrace();
         } catch (IOException e) {
                e.printStackTrace();
         }
         return wb;   
    }
    /**導出xlsx文件
     * https://www.2cto.com/kf/201605/510933.html
     * https://www.cnblogs.com/f-anything/p/5996380.html
     */
    public void outPutToAExcel(List<Teacher> teachers) throws IOException {
        XSSFWorkbook wb=new XSSFWorkbook();
        XSSFCellStyle style=Style.createCellStyle(wb);
        XSSFSheet sheet=wb.createSheet(outPutSheetName);
        //這里的是表格內像素的轉換公式,例如第列寬24像素,第二列寬20像素等等..
        sheet.setColumnWidth(0, 256*24+184);//sheet.setColumnWidth(0, 256*width+184);http://blog.csdn.net/duqian42707/article/details/51491312
        sheet.setColumnWidth(1, 256*20+184);
        sheet.setColumnWidth(2, 256*10+184);
        sheet.setColumnWidth(3, 256*10+184);
        //合並第一行
        CellRangeAddress region1 = new CellRangeAddress(0, 0, (short) 0, (short) 3); //參數1:起始行 參數2:終止行 參數3:起始列 參數4:終止列   
        sheet.addMergedRegion(region1);//合並單元格
        XSSFCell cell_=sheet.createRow(0).createCell(0);
        cell_.setCellStyle(style);
        cell_.setCellValue("                                  學生預約系統教師賬號信息");//手動居中~
        //輸出表頭,即第一行
        XSSFRow row=null;
        XSSFCell cell0_,cell1_,cell2_,cell3_;
        XSSFRow row0=sheet.createRow((int)1);
        XSSFCell cell0=row0.createCell(0);
        XSSFCell cell1=row0.createCell(1);
        XSSFCell cell2=row0.createCell(2);
        XSSFCell cell3=row0.createCell(3);
        //表格樣式
        cell0.setCellStyle(style);
        cell1.setCellStyle(style);
        cell2.setCellStyle(style);
        cell3.setCellStyle(style);
        cell0.setCellValue("郵箱賬號");
        cell1.setCellValue("學科專業");
        cell2.setCellValue("教師姓名");
        cell3.setCellValue("賬號密碼");
        for(int i=0;i<teachers.size();i++){
            row=sheet.createRow(i+2);
            cell0_=row.createCell(0);
            cell1_=row.createCell(1);
            cell2_=row.createCell(2);
            cell3_=row.createCell(3);
            cell0_.setCellStyle(style);
            cell1_.setCellStyle(style);
            cell2_.setCellStyle(style);
            cell3_.setCellStyle(style);
            cell0_.setCellValue(teachers.get(i).getEmail());
            cell1_.setCellValue(teachers.get(i).getMajor());
            cell2_.setCellValue(teachers.get(i).getName());    
            cell3_.setCellValue(teachers.get(i).getPassword());
        }
        try{
            FileOutputStream outputStream=new FileOutputStream(filePath);
            wb.write(outputStream);
            wb.close();
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e){
            System.err.println("獲取不到位置");
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        //導出Excel測試
        TeacherTableEnhanced one=new TeacherTableEnhanced("C:/Users/XPS/Desktop/教師表格.xlsx");//這里需要輸入導出的地址
        List<Teacher> teachers=new ArrayList<Teacher>();
        Teacher a=new Teacher("111@qq.com", "123456", "Eason", "Computer Science");
        teachers.add(a);
        one.outPutToAExcel(teachers);
        
        
        //導入Excel測試
//        TeacherTableEnhanced one=new TeacherTableEnhanced("C:/Users/XPS/Desktop/教師表格.xlsx");//這里需要輸入導入的地址
//        List<Teacher> teachers=one.getFromExcel();//從Excel文件中獲取List
//        for(Teacher a:teachers){
//            System.out.println(a);
//        }
    }

}

 源代碼╰( ̄ω ̄o):https://github.com/Ruukita/Java-Excel


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM