1. 程式人生 > >POI操作Excel詳解---HSSF和XSSF兩種方式

POI操作Excel詳解---HSSF和XSSF兩種方式

HSSF方式:

<span style="font-family:Courier New;">package com.tools.poi.lesson1; 
   
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.text.ParseException; 
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.HSSFCellStyle; 
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.poifs.filesystem.POIFSFileSystem; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.CellStyle; 
   
import com.tools.poi.bean.Student; 
   
public class ExcelUtilWithHSSF { 
    public static void main(String[] args) { 
        try { 
            getExcelAsFile("aaa"); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
           
           
//      try { 
//          CreateExcelDemo1(); 
//      } catch (ParseException e) { 
//          e.printStackTrace(); 
//      } 
           
           
    } 
       
    /**
     * 得到Excel,並解析內容
     * @param file
     * @throws FileNotFoundException
     * @throws IOException
     */ 
    public static void getExcelAsFile(String file) throws FileNotFoundException, IOException{ 
        //1.得到Excel常用物件 
//      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/test.xls")); 
        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls")); 
        //2.得到Excel工作簿物件 
        HSSFWorkbook wb = new HSSFWorkbook(fs); 
        //3.得到Excel工作表物件 
        HSSFSheet sheet = wb.getSheetAt(0); 
        //總行數 
        int trLength = sheet.getLastRowNum(); 
        //4.得到Excel工作表的行 
        HSSFRow row = sheet.getRow(0); 
        //總列數 
        int tdLength = row.getLastCellNum(); 
        //5.得到Excel工作表指定行的單元格 
        HSSFCell cell = row.getCell((short)1); 
        //6.得到單元格樣式 
        CellStyle cellStyle = cell.getCellStyle(); 
        for(int i=0;i<trLength;i++){ 
            //得到Excel工作表的行 
            HSSFRow row1 = sheet.getRow(i); 
            for(int j=0;j<tdLength;j++){ 
                   
            //得到Excel工作表指定行的單元格 
            HSSFCell cell1 = row1.getCell(j); 
               
            /**
             * 為了處理:Excel異常Cannot get a text value from a numeric cell
             * 將所有列中的內容都設定成String型別格式
             */ 
            if(cell1!=null){ 
                  cell1.setCellType(Cell.CELL_TYPE_STRING); 
             } 
               
            //獲得每一列中的值 
            System.out.print(cell1.getStringCellValue()+"\t\t\t"); 
            } 
            System.out.println(); 
        } 
    } 
       
       
    /**
     * 建立Excel,並寫入內容
     */ 
    public static void CreateExcel(){ 
           
        //1.建立Excel工作薄物件 
        HSSFWorkbook wb = new HSSFWorkbook(); 
        //2.建立Excel工作表物件      
        HSSFSheet sheet = wb.createSheet("new Sheet"); 
        //3.建立Excel工作表的行    
        HSSFRow row = sheet.createRow(6); 
        //4.建立單元格樣式 
        CellStyle cellStyle =wb.createCellStyle(); 
          // 設定這些樣式 
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
             
             
             
        //5.建立Excel工作表指定行的單元格 
        row.createCell(0).setCellStyle(cellStyle); 
        //6.設定Excel工作表的值 
        row.createCell(0).setCellValue("aaaa"); 
           
        row.createCell(1).setCellStyle(cellStyle); 
        row.createCell(1).setCellValue("bbbb"); 
           
           
        //設定sheet名稱和單元格內容 
        wb.setSheetName(0,"第一張工作表"); 
        //設定單元格內容   cell.setCellValue("單元格內容"); 
           
        // 最後一步,將檔案存到指定位置 
                try 
                { 
                    FileOutputStream fout = new FileOutputStream("E:/students.xls"); 
                    wb.write(fout); 
                    fout.close(); 
                } 
                catch (Exception e) 
                { 
                    e.printStackTrace(); 
                } 
    } 
       
    /**
     * 建立Excel的例項
     * @throws ParseException 
     */ 
    public static void CreateExcelDemo1() throws ParseException{ 
        List list = new ArrayList(); 
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd"); 
        Student user1 = new Student(1, "張三", 16,true, df.parse("1997-03-12")); 
        Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12")); 
        Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12")); 
        list.add(user1); 
        list.add(user2); 
        list.add(user3); 
           
           
        // 第一步,建立一個webbook,對應一個Excel檔案 
                HSSFWorkbook wb = new HSSFWorkbook(); 
                // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet 
                HSSFSheet sheet = wb.createSheet("學生表一"); 
                // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short 
                HSSFRow row = sheet.createRow((int) 0); 
                // 第四步,建立單元格,並設定值表頭 設定表頭居中 
                HSSFCellStyle style = wb.createCellStyle(); 
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式 
   
                HSSFCell cell = row.createCell((short) 0); 
                cell.setCellValue("學號"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 1); 
                cell.setCellValue("姓名"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 2); 
                cell.setCellValue("年齡"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 3); 
                cell.setCellValue("性別"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 4); 
                cell.setCellValue("生日"); 
                cell.setCellStyle(style); 
   
                // 第五步,寫入實體資料 實際應用中這些資料從資料庫得到, 
   
                for (int i = 0; i < list.size(); i++) 
                { 
                    row = sheet.createRow((int) i + 1); 
                    Student stu = (Student) list.get(i); 
                    // 第四步,建立單元格,並設定值 
                    row.createCell((short) 0).setCellValue((double) stu.getId()); 
                    row.createCell((short) 1).setCellValue(stu.getName()); 
                    row.createCell((short) 2).setCellValue((double) stu.getAge()); 
                    row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女"); 
                    cell = row.createCell((short) 4); 
                    cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu 
                            .getBirthday())); 
                } 
                // 第六步,將檔案存到指定位置 
                try 
                { 
                    FileOutputStream fout = new FileOutputStream("E:/students.xls"); 
                    wb.write(fout); 
                    fout.close(); 
                } 
                catch (Exception e) 
                { 
                    e.printStackTrace(); 
                } 
           
           
           
    } 
}</span>
XSSF方式:
<span style="font-family:Courier New;">package com.tools.poi.lesson1; 
   
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.text.ParseException; 
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.HSSFCellStyle; 
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.openxml4j.exceptions.InvalidFormatException; 
import org.apache.poi.poifs.filesystem.POIFSFileSystem; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.CellStyle; 
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.usermodel.WorkbookFactory; 
import org.apache.poi.ss.util.WorkbookUtil; 
   
import com.tools.poi.bean.Student; 
   
public class ExcelUtilWithXSSF { 
    public static void main(String[] args) { 
        try { 
            getExcelAsFile("d:/FTP/系統報表.xls"); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } catch (InvalidFormatException e) { 
            e.printStackTrace(); 
        } 
           
           
//      try { 
//          CreateExcelDemo1(); 
//      } catch (ParseException e) { 
//          e.printStackTrace(); 
//      } 
           
           
    } 
       
    /**
     * 得到Excel,並解析內容  對2007及以上版本 使用XSSF解析
     * @param file
     * @throws FileNotFoundException
     * @throws IOException
     * @throws InvalidFormatException 
     */ 
    public static void getExcelAsFile(String file) throws FileNotFoundException, IOException, InvalidFormatException{ 
//      //1.得到Excel常用物件 
//      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls")); 
//      //2.得到Excel工作簿物件 
//      HSSFWorkbook wb = new HSSFWorkbook(fs); 
   
           
           
        InputStream ins = null;    
        Workbook wb = null;    
            ins=new FileInputStream(new File(file));    
            //ins= ExcelService.class.getClassLoader().getResourceAsStream(filePath);    
            wb = WorkbookFactory.create(ins);    
            ins.close();    
           
           
        //3.得到Excel工作表物件 
        Sheet sheet = wb.getSheetAt(0); 
        //總行數 
        int trLength = sheet.getLastRowNum(); 
        //4.得到Excel工作表的行 
        Row row = sheet.getRow(0); 
        //總列數 
        int tdLength = row.getLastCellNum(); 
        //5.得到Excel工作表指定行的單元格 
        Cell cell = row.getCell((short)1); 
        //6.得到單元格樣式 
        CellStyle cellStyle = cell.getCellStyle(); 
   
        for(int i=5;i<trLength;i++){ 
            //得到Excel工作表的行 
            Row row1 = sheet.getRow(i); 
            for(int j=0;j<tdLength;j++){ 
            //得到Excel工作表指定行的單元格 
            Cell cell1 = row1.getCell(j); 
            /**
             * 為了處理:Excel異常Cannot get a text value from a numeric cell
             * 將所有列中的內容都設定成String型別格式
             */ 
            if(cell1!=null){ 
                  cell1.setCellType(Cell.CELL_TYPE_STRING); 
             } 
               
            if(j==5&&i<=10){ 
                cell1.setCellValue("1000"); 
            } 
               
            //獲得每一列中的值 
            System.out.print(cell1+"                   "); 
            } 
            System.out.println(); 
        } 
           
        //將修改後的資料儲存 
        OutputStream out = new FileOutputStream(file); 
                wb.write(out); 
    } 
       
       
    /**
     * 建立Excel,並寫入內容
     */ 
    public static void CreateExcel(){ 
           
        //1.建立Excel工作薄物件 
        HSSFWorkbook wb = new HSSFWorkbook(); 
        //2.建立Excel工作表物件      
        HSSFSheet sheet = wb.createSheet("new Sheet"); 
        //3.建立Excel工作表的行    
        HSSFRow row = sheet.createRow(6); 
        //4.建立單元格樣式 
        CellStyle cellStyle =wb.createCellStyle(); 
          // 設定這些樣式 
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); 
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
             
             
             
        //5.建立Excel工作表指定行的單元格 
        row.createCell(0).setCellStyle(cellStyle); 
        //6.設定Excel工作表的值 
        row.createCell(0).setCellValue("aaaa"); 
           
        row.createCell(1).setCellStyle(cellStyle); 
        row.createCell(1).setCellValue("bbbb"); 
           
           
        //設定sheet名稱和單元格內容 
        wb.setSheetName(0,"第一張工作表"); 
        //設定單元格內容   cell.setCellValue("單元格內容"); 
           
        // 最後一步,將檔案存到指定位置 
                try 
                { 
                    FileOutputStream fout = new FileOutputStream("E:/students.xls"); 
                    wb.write(fout); 
                    fout.close(); 
                } 
                catch (Exception e) 
                { 
                    e.printStackTrace(); 
                } 
    } 
       
    /**
     * 建立Excel的例項
     * @throws ParseException 
     */ 
    public static void CreateExcelDemo1() throws ParseException{ 
        List list = new ArrayList(); 
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd"); 
        Student user1 = new Student(1, "張三", 16,true, df.parse("1997-03-12")); 
        Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12")); 
        Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12")); 
        list.add(user1); 
        list.add(user2); 
        list.add(user3); 
           
           
        // 第一步,建立一個webbook,對應一個Excel檔案 
                HSSFWorkbook wb = new HSSFWorkbook(); 
                // 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet 
                HSSFSheet sheet = wb.createSheet("學生表一"); 
                // 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short 
                HSSFRow row = sheet.createRow((int) 0); 
                // 第四步,建立單元格,並設定值表頭 設定表頭居中 
                HSSFCellStyle style = wb.createCellStyle(); 
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式 
   
                HSSFCell cell = row.createCell((short) 0); 
                cell.setCellValue("學號"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 1); 
                cell.setCellValue("姓名"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 2); 
                cell.setCellValue("年齡"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 3); 
                cell.setCellValue("性別"); 
                cell.setCellStyle(style); 
                cell = row.createCell((short) 4); 
                cell.setCellValue("生日"); 
                cell.setCellStyle(style); 
   
                // 第五步,寫入實體資料 實際應用中這些資料從資料庫得到, 
   
                for (int i = 0; i < list.size(); i++) 
                { 
                    row = sheet.createRow((int) i + 1); 
                    Student stu = (Student) list.get(i); 
                    // 第四步,建立單元格,並設定值 
                    row.createCell((short) 0).setCellValue((double) stu.getId()); 
                    row.createCell((short) 1).setCellValue(stu.getName()); 
                    row.createCell((short) 2).setCellValue((double) stu.getAge()); 
                    row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女"); 
                    cell = row.createCell((short) 4); 
                    cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu 
                            .getBirthday())); 
                } 
                // 第六步,將檔案存到指定位置 
                try 
                { 
                    FileOutputStream fout = new FileOutputStream("E:/students.xls"); 
                    wb.write(fout); 
                    fout.close(); 
                } 
                catch (Exception e) 
                { 
                    e.printStackTrace(); 
                } 
           
           
           
    } 
}</span>

注意:

修改Excel中的某個內容:

cell1.setCellValue("1000"); 

儲存修改後的Excel檔案:

OutputStream out = new FileOutputStream(file);
wb.write(out);

相關推薦

POI操作Excel---HSSFXSSF方式

HSSF方式: <span style="font-family:Courier New;">package com.tools.poi.lesson1;      import java.io.FileInputStream;  import java.io.

POI操作ExcelHSSFXSSF方式

HSSF方式: package com.tools.poi.lesson1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; impor

POI操作excelHSSFXSSF方式的區別

HSSF方式: [java] view plain copy print?package com.tools.poi.lesson1;  import java.io.FileInputStream;  import java.io.FileNotFoundException;  import java.

POI操作Excel,讀取xlsxlsx格式的文件

shee xss split 類型 後綴 .sh lan xls lin package org.ian.webutil; import java.io.File; import java.io.FileInputStream; import java.io.FileN

Linux 下Redis叢集安裝部署及使用(線上離線安裝+相關錯誤解決方案)

一、應用場景介紹   本文主要是介紹Redis叢集在Linux環境下的安裝講解,其中主要包括在聯網的Linux環境和離線的Linux環境下是如何安裝的。因為大多數時候,公司的生產環境是在內網環境下,無外網,伺服器處於離線狀態(最近公司要上線專案,就是無外網環境的Linux,被離線安裝坑慘了,走了很多彎路,說多

POI操作Excel:密碼保護公式再計算

算sheet1.setForceFormulaRecalculation(true);// 寫入excel檔案fileOut = new FileOutputStream("d:/workbook.xls");wb.write(fileOut);fileOut.close();} catch (IOExcep

POI讀寫資料 相容HSSFXSSF

//poi資料型別處理 try {//WorkbookFactory相容HSSF(2003)和XSSF(2007) Workbook wb = WorkbookFactory.create(new FileInputStream(new File("D:\\測試

Redis - SpringBoot整合Redis,RedisTemplate註解方式的使用

本文主要講 Redis 的使用,如何與 SpringBoot 專案整合,如何使用註解方式和 RedisTemplate 方式實現快取。最後會給一個用 Redis 實現分散式鎖,用在秒殺系統中的案例。 更多 Redis 的實際運用場景請關注開源專案 coderiver 專案地址:github.com/cac

代理模式的(一)---SpringAOP的實現代理模式的詳細解讀

   現在在生活中,許多軟體系統都提供跨網路和系統的應用,但在跨網路和系統應用時,作為系統開發者並不希望客戶直接訪問系統中的物件。其中原因很多考慮到系統安全和效能因素,因素還有很多,也就不再進行一一的列舉了,所以,想到了在客戶端和系統端新增一層中間層----代理層,也是即將要介紹的代理模式。   首先,明確

spring之AOP操作(基於aspectJ實現)--配置檔案註解方式實現

AOP概念   1 aop:面向切面(方面)程式設計,擴充套件功能不修改原始碼實現     2  AOP採取橫向抽取機制,取代了傳統縱向繼承體系重複性程式碼     3 aop底層使用動態代理實現     (1)第一種情況,有介面情況,使用動態代理建立介面實現類代理物

跨域的幾方式

小編推薦:Fundebug專注於JavaScript、微信小程式、微信小遊戲,Node.js和Java實時BUG監控。真的是一個很好用的bug監控費服務,眾多大佬公司都在使用。 一、什麼是跨域 JavaScript出於安全方面的考慮,不允許跨域呼叫其他頁面的物件。那什麼是

php5 的 session 之二:有方法傳遞 一個會話 ID:

cookie URL 引數 會話模組支援這兩種方法。cookie 更優化,但由於不總是可用,也提供替代的方法。第二種方法直接將會話 ID 嵌入到 URL 中間去。PHP 可以透明地轉換連線。除非是使用 PHP 4.2 或更低版本,需要手工在編譯PHP 時啟用。在 Unix

Android以JSONOjectGSON方式解析json

length pre ray oid 字符 CA clas img name json文件如下: 將獲取到的json數據轉化為String形式 OkHttpClient client = new OkHttpClient(); R

JDBC中Oracle的SIDServiceName方式的連接字符串格式

bottom none color bubuko div nbsp rac 字符串 padding SID格式: jdbc:oracle:thin:@<host>:<port>:<SID> 如: jdbc:oracle:thin:@19

9.10 路由控制之反向解析--【別名】htmlviews方式實現

com 反向 技術分享 http mage login gin bsp 分享圖片 1. 在html裏反向解析 給路徑起別名,修改路徑時,不用每個地方都修改。 {% url ‘Log‘ %} : 就會去找別名為Log的URL,找到 "login/"後把"logi

julia開發環境安裝——VS code擴充套件JuliaPro方式

VS code擴充套件方式 首先,下載安裝julia1.0.0:我的上一篇文章 完成後,配置系統環境變數: 控制面板\所有控制面板項\系統–>高階系統設定 高階欄下點選系統變數~ 如圖: 在path下新增你的julia/bin路徑如(圖):G:\Julia-1.0.0

Map集合的遍歷方式以及TreeMap集合儲存自定義物件實現比較的ComparableComparator方式

Map集合的特點 1、Map集合中儲存的都是鍵值對,鍵和值是一一對應的 2、一個對映不能包含重複的值 3、每個鍵最多隻能對映到一個值上   Map介面和Collection介面的不同 Map是雙列集合的根介面,Collection是單列集合的根介面 1、Map是雙列的(是雙列集合的根介

mysqldumpxtrabackup方式進行非空庫複製搭建

mysqldump和xtrabackup兩種方式進行非空庫複製搭建 1、mysqldump非空庫複製搭建 2、xtrabackup非空庫複製搭建 mysqldump和xtrabackup兩種方式進行非空庫複製搭建 1、mysqldu

玩轉SpringCloud 三.斷路器(Hystrix)RestTemplate+RibbonFeign方式

 此文章基於: 三.斷路器(Hystrix) 在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以相互呼叫(RPC),在Spring Cloud可以用來呼叫。為了保證其高可用,單個服務通常會叢集部署。由於網路原因或者自身的原因,服務並不能保證100%可用,如果單個服務出現問

第一個django專案-通過命令列pycharm方式

以本機環境為例,ip地址為172.20.16.148,windows平臺,虛擬環境路徑為d:\VirtualEnv,專案存放位置為d:\DjangoProject   命令列方式 1.進入虛擬環境建立專案django-admin startproject projectname 專案的存