四、poi.jar生成excle、sheet.getLastRowNum()統計sheet行數不准確問題修改


1、本章介紹使用poi.jar生成excel
由於在https://www.cnblogs.com/jiarui-zjb/p/7580440.html 該章節中對poi.jar做了相介紹,本章不再贅述,網上博友們寫過有很多的demo,我只是想復習一下知識點,直接上代碼了。
簡單示列1:創建excle

 1 import java.io.FileInputStream;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 import org.apache.poi.hssf.usermodel.HSSFCell;
 7 import org.apache.poi.hssf.usermodel.HSSFRow;
 8 import org.apache.poi.hssf.usermodel.HSSFSheet;
 9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
10 import org.apache.poi.ss.usermodel.Cell;
11 import org.apache.poi.ss.usermodel.Row;
12 import org.apache.poi.ss.usermodel.Sheet;
13 import org.apache.poi.ss.util.CellRangeAddress;
14 import org.junit.Test;
15 /**
16  * 
17  * @classDesc: 功能描述:使用poi工具包實現excle導出
18  *                 1)在本地 D:\ceshiZJB\createExcle目錄下  創建新文件:POIExcel文件示例.xls
19  *              2)實現標題行:合並單元格,行寬為40,列高為30
20  * @author: zjb
21  * @createTime: 創建時間:2018-8-3 下午6:49:18
22  * @version: v1.0
23  * @copyright:pactera
24  */
25 public class PoiTest1_New {
26     public static void main(String[] args){
27         PoiTest1_New poiTest=new PoiTest1_New();
28         try {
29             poiTest.makeExcleByPOI();
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33     }
34     public void makeExcleByPOI() throws Exception {
35         // 1. 創建HSSFWorkbook對象(excel的文檔對象)
36         HSSFWorkbook wb = new HSSFWorkbook();
37         // 2. 建立新的sheet對象(excel的表單)
38         HSSFSheet sheet = wb.createSheet("成績表");
39         sheet.setDefaultRowHeightInPoints(30);// 設置缺省列高
40         sheet.setDefaultColumnWidth(40);// 設置缺省列寬
41         //3. 操作單元格
42         // 3.1 創建行對象,參數為行索引:可以是0~65535之間的任何一個
43         HSSFRow row1 = sheet.createRow(0);
44         // 3.2用行對象創建單元格對象,參數為列索引:可以是0~255之間的任何一個
45         HSSFCell cell = row1.createCell(0);
46         // 設置單元格內容
47         cell.setCellValue("學員考試成績一覽表");
48         // 合並單元格CellRangeAddress構造參數依次表示起始行,截至行,起始列, 截至列
49         sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
50         // 在sheet里創建第二行
51         HSSFRow row2 = sheet.createRow(1);
52         // 創建單元格並設置單元格內容
53         row2.createCell(0).setCellValue("姓名");
54         row2.createCell(1).setCellValue("班級");
55         row2.createCell(2).setCellValue("筆試成績");
56         row2.createCell(3).setCellValue("機試成績");
57         // 在sheet里創建第三行
58         HSSFRow row3 = sheet.createRow(2);
59         row3.createCell(0).setCellValue("李明");
60         row3.createCell(1).setCellValue("As178");
61         row3.createCell(2).setCellValue(87);
62         row3.createCell(3).setCellValue(78);
63         HSSFRow row4 = sheet.createRow(3);
64         row4.createCell(0).setCellValue("龐少");
65         row4.createCell(1).setCellValue("As179");
66         row4.createCell(2).setCellValue(87);
67         row4.createCell(3).setCellValue(78);
68         // .....省略部分代碼
69         // 輸出Excel文件
70         FileOutputStream output = new FileOutputStream("D:\\ceshiZJB\\createExcle\\POIExcel文件示例.xls");
71         wb.write(output);
72         output.flush();
73         output.close();
74     }
75 }
View Code

簡單示列2:讀取示列1中生成的樣板,進行創建excle

  1 import java.io.FileInputStream;
  2 import java.io.FileOutputStream;
  3 import java.io.IOException;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import org.apache.poi.hssf.usermodel.HSSFCell;
  7 import org.apache.poi.hssf.usermodel.HSSFRow;
  8 import org.apache.poi.hssf.usermodel.HSSFSheet;
  9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 10 import org.apache.poi.ss.usermodel.Cell;
 11 import org.apache.poi.ss.usermodel.Row;
 12 import org.apache.poi.ss.usermodel.Sheet;
 13 import org.apache.poi.ss.util.CellRangeAddress;
 14 import org.junit.Test;
 15 /**
 16  * 
 17  * @classDesc: 功能描述:使用poi工具包實現excle導出
 18  *                 1)在本地  通過讀取本地文件:POIExcel文件示例.xls,創建新的 POIExcel文件示例_new1.xls
 19  *                 2)讀取第四行內容放入:temp這個數組中,並進行輸出
 20  * @author: zjb
 21  * @createTime: 創建時間:2018-8-3 下午6:49:18
 22  * @version: v1.0
 23  * @copyright:pactera
 24  */
 25 public class PoiTest2_modifySimple {
 26     public static void main(String[] args){
 27         PoiTest2_modifySimple poiTest=new PoiTest2_modifySimple();
 28         try {
 29             poiTest.loadScoreInfo();
 30         } catch (IOException e) {
 31             e.printStackTrace();
 32         }
 33     }
 34     public void loadScoreInfo() throws IOException {
 35         ArrayList temp = new ArrayList();
 36         FileInputStream fileIn = new FileInputStream("D:\\ceshiZJB\\createExcle\\POIExcel文件示例.xls");
 37         //輸出模板
 38         FileOutputStream out = new FileOutputStream("D:\\ceshiZJB\\createExcle\\POIExcel文件示例_new1.xls");
 39         //1. 根據指定的文件輸入流導入Excel從而產生Workbook對象
 40         HSSFWorkbook workBook = new HSSFWorkbook(fileIn);
 41         //2. 獲取Excel文檔中的第一個表單
 42         Sheet sht0 = workBook.getSheetAt(0);
 43         // 對Sheet中的每一行進行迭代
 44         for (Row r : sht0) {
 45             System.out.println("Sheet是一個集合,集合中存放的是行對象,獲取當前行對象-->"+r);
 46             // 如果當前行的行號(從0開始)未達到3(第四行)則從新循環
 47             System.out.println("r.getRowNum()--起始->"+r.getRowNum());
 48             if (r.getRowNum() < 3) {
 49                 continue;
 50             }
 51             System.out.println("r.getRowNum()--->"+r.getRowNum());
 52             // 創建實體類
 53             ScoreInfo info = new ScoreInfo();
 54             // 取出當前行第1個單元格數據,並封裝在info實體stuName屬性上
 55             System.out.println("r.getCell(0).getStringCellValue()-->"+r.getCell(0).getStringCellValue());
 56             info.setStuName(r.getCell(0).getStringCellValue());
 57             System.out.println("r.getCell(1).getStringCellValue()-->"+r.getCell(1).getStringCellValue());
 58             info.setClassName(r.getCell(1).getStringCellValue());
 59             System.out.println("r.getCell(2).getNumericCellValue()-->"+r.getCell(2).getNumericCellValue());
 60             info.setWrittenScores(r.getCell(2).getNumericCellValue());
 61             System.out.println("r.getCell(3).getNumericCellValue()-->"+r.getCell(3).getNumericCellValue());
 62             info.setMachineScores(r.getCell(3).getNumericCellValue());
 63             temp.add(info);
 64             System.err.println("info--->"+info);
 65             workBook.write(out);
 66             out.flush();
 67             out.close();
 68         }
 69         fileIn.close();
 70     }
 71 }
 72 /**
 73  * 
 74  * @classDesc: 功能描述:實體類
 75  * @author: zjb
 76  * @createTime: 創建時間:2018-8-3 下午6:51:07
 77  * @version: v1.0
 78  * @copyright:pactera
 79  */
 80 
 81 public class ScoreInfo {
 82     private String StuName;
 83     private String ClassName;
 84     private double WrittenScores;
 85     private double MachineScores;
 86     
 87     public String getStuName() {
 88         return StuName;
 89     }
 90     public void setStuName(String stuName) {
 91         StuName = stuName;
 92     }
 93     public String getClassName() {
 94         return ClassName;
 95     }
 96     public void setClassName(String className) {
 97         ClassName = className;
 98     }
 99     public double getWrittenScores() {
100         return WrittenScores;
101     }
102     public void setWrittenScores(double writtenScores) {
103         WrittenScores = writtenScores;
104     }
105     public double getMachineScores() {
106         return MachineScores;
107     }
108     public void setMachineScores(double machineScores) {
109         MachineScores = machineScores;
110     }
111     @Override
112     public String toString() {
113         return "ScoreInfo [StuName=" + StuName + ", ClassName=" + ClassName
114                 + ", WrittenScores=" + WrittenScores + ", MachineScores="
115                 + MachineScores + "]";
116     }
117 }
View Code

2、poi通過sheet.getLastRowNum() 獲取當前sheet頁行數時會將行內容為空,但是存在樣式的行進行統計,導致獲取的最大行數不准確
可通過將空白行(內容為空,但是存在樣式)進行刪除后再調用getLastRowNum()進行行數統計

sheet0=getAccuracyContextNum(book);
int allRownum=sheet0.getLastRowNum();

//獲取准確的文件行數
public Sheet getAccuracyContextNum(Workbook workbook) {
    // 取第一個sheet
    Sheet sheet = workbook.getSheetAt(0);
    // 刪除空行
    for (int i = 0; i <= sheet.getLastRowNum(); i++) {
        Row row = sheet.getRow(i);
        // 刪除空行
        if (this.isRowEmpty(row)) {
            int lastRowNum = sheet.getLastRowNum();
            if (i >= 0 && i < lastRowNum) {
                sheet.shiftRows(i + 1, lastRowNum, -1);// 將行號為i+1一直到行號為lastRowNum的單元格全部上移一行,以便刪除i行
            }
            if (i == lastRowNum) {
                if (row != null) {
                    sheet.removeRow(row);
                }
            }
            i--;
        }
    }
    return sheet;
}
View Code

 


免責聲明!

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



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