自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java:實現(xiàn)文件批量導(dǎo)入導(dǎo)出實踐(兼容xls,xlsx)

開發(fā) 后端
本文主要介紹HSSF和XSSF兩種組件,簡單的講HSSF用來操作Office 2007版本前excel.xls文件,XSSF用來操作Office 2007版本后的excel.xlsx文件,注意二者的后綴是不一樣的。

[[315627]]

1、介紹

java實現(xiàn)文件的導(dǎo)入導(dǎo)出數(shù)據(jù)庫,目前在大部分系統(tǒng)中是比較常見的功能了,今天寫個小demo來理解其原理,沒接觸過的同學(xué)也可以看看參考下。

目前我所接觸過的導(dǎo)入導(dǎo)出技術(shù)主要有POI和iReport,poi主要作為一些數(shù)據(jù)批量導(dǎo)入數(shù)據(jù)庫,iReport做報表導(dǎo)出。另外還有jxl類似poi的方式,不過貌似很久沒跟新了,2007之后的office好像也不支持,這里就不說了。

2、POI使用詳解

2.1 什么是Apache POI?

Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。

2.2 POI的jar包導(dǎo)入

本次講解使用maven工程,jar包版本使用poi-3.14和poi-ooxml-3.14。目前最新的版本是3.16。因為3.15以后相關(guān)api有更新,部分操作可能不一樣,大家注意下。 

  1. <!-- poi的包 3.15版本后單元格類型獲取方式有調(diào)整 -->  
  2.         <dependency>  
  3.             <groupId>org.apache.poi</groupId>  
  4.             <artifactId>poi</artifactId>  
  5.             <version>3.14</version>  
  6.         </dependency>  
  7.         <dependency>  
  8.             <groupId>org.apache.poi</groupId>  
  9.             <artifactId>poi-ooxml</artifactId>  
  10.             <version>3.14</version>  
  11.         </dependency> 

2.3 POI的API講解

2.3.1 結(jié)構(gòu)

HSSF - 提供讀寫Microsoft Excel格式檔案的功能。

XSSF - 提供讀寫Microsoft Excel OOXML格式檔案的功能。

HWPF - 提供讀寫Microsoft Word格式檔案的功能。

HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。

HDGF - 提供讀寫Microsoft Visio格式檔案的功能。

2.3.2 對象

本文主要介紹HSSF和XSSF兩種組件,簡單的講HSSF用來操作Office 2007版本前excel.xls文件,XSSF用來操作Office 2007版本后的excel.xlsx文件,注意二者的后綴是不一樣的。

HSSF在org.apache.poi.hssf.usermodel包中。它實現(xiàn)了Workbook 接口,用于Excel文件中的.xls格式

常用組件:

HSSFWorkbook : excel的文檔對象

HSSFSheet : excel的表單

HSSFRow : excel的行

HSSFCell : excel的格子單元

HSSFFont : excel字體

HSSFDataFormat: 日期格式

HSSFHeader : sheet頭

HSSFFooter : sheet尾(只有打印的時候才能看到效果)

樣式:

HSSFCellStyle : cell樣式

輔助操作包括:

HSSFDateUtil : 日期

HSSFPrintSetup : 打印

HSSFErrorConstants : 錯誤信息表

XSSF在org.apache.xssf.usemodel包,并實現(xiàn)Workbook接口,用于Excel文件中的.xlsx格式

常用組件:

XSSFWorkbook : excel的文檔對象

XSSFSheet: excel的表單

XSSFRow: excel的行

XSSFCell: excel的格子單元

XSSFFont: excel字體

XSSFDataFormat : 日期格式

和HSSF類似;

2.3.3 兩個組件共同的字段類型描述

其實兩個組件就是針對excel的兩種格式,大部分的操作都是相同的。

2.3.4 操作步驟

以HSSF為例,XSSF操作相同。

首先,理解一下一個Excel的文件的組織形式,一個Excel文件對應(yīng)于一個workbook(HSSFWorkbook),一個workbook可以有多個sheet(HSSFSheet)組成,一個sheet是由多個row(HSSFRow)組成,一個row是由多個cell(HSSFCell)組成。

1、用HSSFWorkbook打開或者創(chuàng)建“Excel文件對象”

2、用HSSFWorkbook對象返回或者創(chuàng)建Sheet對象

3、用Sheet對象返回行對象,用行對象得到Cell對象

4、對Cell對象讀寫。

3、代碼操作

3.1 效果圖

慣例,貼代碼前先看效果圖

Excel文件兩種格式各一個:

代碼結(jié)構(gòu):

導(dǎo)入后:(我導(dǎo)入了兩遍,沒做校驗)

導(dǎo)出效果:

3.2 代碼詳解

這里我以Spring+SpringMVC+Mybatis為基礎(chǔ),擴(kuò)展:SpringBoot+Mybatis多模塊(module)項目搭建教程

Controller: 

  1. package com.allan.controller;  
  2. import java.util.List;  
  3. import javax.servlet.http.HttpServletResponse;  
  4. import org.apache.poi.ss.formula.functions.Mode;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.Model;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestMethod;  
  10. import org.springframework.web.bind.annotation.RequestParam;  
  11. import org.springframework.web.bind.annotation.ResponseBody;  
  12. import org.springframework.web.multipart.MultipartFile;  
  13. import org.springframework.web.servlet.ModelAndView;  
  14. import com.allan.pojo.Student;  
  15. import com.allan.service.StudentService;  
  16. /**  
  17.  *   
  18.  * @author 小賣鋪的老爺爺  
  19.  *  
  20.  */  
  21. @Controller  
  22. public class StudentController {  
  23.     @Autowired  
  24.     private StudentService studentService;  
  25.     /**  
  26.      * 批量導(dǎo)入表單數(shù)據(jù)  
  27.      *   
  28.      * @param request  
  29.      * @param myfile  
  30.      * @return  
  31.      */  
  32.     @RequestMapping(value="/importExcel",method=RequestMethod.POST)  
  33.     public String importExcel(@RequestParam("myfile") MultipartFile myFile) {  
  34.         ModelAndView modelAndView = new ModelAndView();  
  35.         try {  
  36.             Integer num = studentService.importExcel(myFile);  
  37.         } catch (Exception e) {  
  38.             modelAndView.addObject("msg", e.getMessage());  
  39.             return "index";  
  40.         }  
  41.         modelAndView.addObject("msg", "數(shù)據(jù)導(dǎo)入成功");  
  42.         return "index";  
  43.     }  
  44.     @RequestMapping(value="/exportExcel",method=RequestMethod.GET)  
  45.     public void exportExcel(HttpServletResponse response) {      
  46.         try {  
  47.             studentService.exportExcel(response);  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.     }  

Service 

  1. package com.allan.service.impl;  
  2. import java.io.OutputStream;  
  3. import java.text.DecimalFormat;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6. import java.util.List;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import org.apache.commons.lang.StringUtils;  
  9. import org.apache.poi.hssf.usermodel.HSSFCell;  
  10. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  11. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  12. import org.apache.poi.hssf.usermodel.HSSFRow;  
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  15. import org.apache.poi.ss.usermodel.Cell;  
  16. import org.apache.poi.ss.usermodel.Row;  
  17. import org.apache.poi.ss.usermodel.Sheet;  
  18. import org.apache.poi.ss.usermodel.Workbook;  
  19. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  20. import org.springframework.beans.factory.annotation.Autowired;  
  21. import org.springframework.stereotype.Service;  
  22. import org.springframework.web.multipart.MultipartFile;  
  23. import com.allan.mapper.StudentMapper;  
  24. import com.allan.pojo.Student;  
  25. import com.allan.service.StudentService;  
  26. /**  
  27.  *   
  28.  * @author 小賣鋪的老爺爺  
  29.  *  
  30.  */  
  31. @Service  
  32. public class StudentServiceImpl implements StudentService{  
  33.     private final static String XLS = "xls";    
  34.     private final static String XLSX = "xlsx";   
  35.     @Autowired  
  36.     private StudentMapper studentMapper;  
  37.     /**  
  38.      * 導(dǎo)入Excel,兼容xls和xlsx  
  39.      */  
  40.     @SuppressWarnings("resource")  
  41.     public Integer importExcel(MultipartFile myFile) throws Exception {  
  42.         //        1、用HSSFWorkbook打開或者創(chuàng)建“Excel文件對象”  
  43.         //  
  44.         //        2、用HSSFWorkbook對象返回或者創(chuàng)建Sheet對象  
  45.         //  
  46.         //        3、用Sheet對象返回行對象,用行對象得到Cell對象  
  47.         //  
  48.         //        4、對Cell對象讀寫。  
  49.         //獲得文件名    
  50.         Workbook workbook = null ;  
  51.         String fileName = myFile.getOriginalFilename();   
  52.         if(fileName.endsWith(XLS)){    
  53.             //2003   
  54.              workbook = new HSSFWorkbook(myFile.getInputStream());    
  55.         }else if(fileName.endsWith(XLSX)){    
  56.             //2007    
  57.             workbook = new XSSFWorkbook(myFile.getInputStream());    
  58.         }else{  
  59.             throw new Exception("文件不是Excel文件");  
  60.         }  
  61.         Sheet sheet = workbook.getSheet("Sheet1");  
  62.         int rows = sheet.getLastRowNum();// 指的行數(shù),一共有多少行+  
  63.         if(rows==0){  
  64.             throw new Exception("請?zhí)顚憯?shù)據(jù)");  
  65.         }  
  66.         for (int i = 1; i <= rows+1; i++) {  
  67.             // 讀取左上端單元格  
  68.             Row row = sheet.getRow(i);  
  69.             // 行不為空  
  70.             if (row != null) {  
  71.                 // **讀取cell**  
  72.                 Student student = new Student();  
  73.                 //姓名  
  74.                 String name = getCellValue(row.getCell(0));  
  75.                 student.setName(name);  
  76.                 //班級  
  77.                 String classes = getCellValue(row.getCell(1));  
  78.                 student.setClasses(classes);  
  79.                 //分?jǐn)?shù)  
  80.                 String scoreString = getCellValue(row.getCell(2));  
  81.                 if (!StringUtils.isEmpty(scoreString)) {  
  82.                     Integer score = Integer.parseInt(scoreString);  
  83.                     student.setScore(score);  
  84.                 }  
  85.                 //考試時間  
  86.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小寫的mm表示的是分鐘   
  87.                 String dateString = getCellValue(row.getCell(3));    
  88.                 if (!StringUtils.isEmpty(dateString)) {  
  89.                     Date date=sdf.parse(dateString);    
  90.                     student.setTime(date);  
  91.                 }  
  92.                 studentMapper.insert(student);  
  93.             }  
  94.         }  
  95.         return rows-1;  
  96.     } 
  97.     /**  
  98.      * 獲得Cell內(nèi)容  
  99.      *   
  100.      * @param cell  
  101.      * @return  
  102.      */  
  103.     public String getCellValue(Cell cell) {  
  104.         String value = "" 
  105.         if (cell != null) {  
  106.             // 以下是判斷數(shù)據(jù)的類型  
  107.             switch (cell.getCellType()) {  
  108.             case HSSFCell.CELL_TYPE_NUMERIC: // 數(shù)字  
  109.                 value = cell.getNumericCellValue() + "";  
  110.                 if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  111.                     Date date = cell.getDateCellValue();  
  112.                     if (date != null) {  
  113.                         value = new SimpleDateFormat("yyyy-MM-dd").format(date);  
  114.                     } else {  
  115.                         value = "" 
  116.                     }  
  117.                 } else {  
  118.                     value = new DecimalFormat("0").format(cell.getNumericCellValue());  
  119.                 }  
  120.                 break;  
  121.             case HSSFCell.CELL_TYPE_STRING: // 字符串  
  122.                 value = cell.getStringCellValue();  
  123.                 break;  
  124.             case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
  125.                 value = cell.getBooleanCellValue() + "";  
  126.                 break;  
  127.             case HSSFCell.CELL_TYPE_FORMULA: // 公式  
  128.                 value = cell.getCellFormula() + "";  
  129.                 break;  
  130.             case HSSFCell.CELL_TYPE_BLANK: // 空值  
  131.                 value = "" 
  132.                 break;  
  133.             case HSSFCell.CELL_TYPE_ERROR: // 故障  
  134.                 value = "非法字符" 
  135.                 break;  
  136.             default:  
  137.                 value = "未知類型" 
  138.                 break;  
  139.             }  
  140.         }  
  141.         return value.trim();  
  142.     }  
  143.     /**  
  144.      * 導(dǎo)出excel文件  
  145.      */  
  146.     public void exportExcel(HttpServletResponse response) throws Exception {  
  147.         // 第一步,創(chuàng)建一個webbook,對應(yīng)一個Excel文件    
  148.         HSSFWorkbook wb = new HSSFWorkbook();    
  149.         // 第二步,在webbook中添加一個sheet,對應(yīng)Excel文件中的sheet    
  150.         HSSFSheet sheet = wb.createSheet("Sheet1");    
  151.         // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數(shù)列數(shù)有限制short    
  152.         HSSFRow row = sheet.createRow(0);    
  153.         // 第四步,創(chuàng)建單元格,并設(shè)置值表頭 設(shè)置表頭居中    
  154.         HSSFCellStyle style = wb.createCellStyle();    
  155.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創(chuàng)建一個居中格式    
  156.         HSSFCell cell = row.createCell(0);  
  157.         cell.setCellValue("姓名");    
  158.         cell.setCellStyle(style);    
  159.         cell = row.createCell(1);    
  160.         cell.setCellValue("班級");    
  161.         cell.setCellStyle(style);    
  162.         cell = row.createCell(2);    
  163.         cell.setCellValue("分?jǐn)?shù)");    
  164.         cell.setCellStyle(style);    
  165.         cell = row.createCell(3);    
  166.         cell.setCellValue("時間");    
  167.         cell.setCellStyle(style);    
  168.         // 第五步,寫入實體數(shù)據(jù) 實際應(yīng)用中這些數(shù)據(jù)從數(shù)據(jù)庫得到,   
  169.         List<Student> list = studentMapper.selectAll();    
  170.         for (int i = 0; i < list.size(); i++){    
  171.             row = sheet.createRow(i + 1);    
  172.             Student stu = list.get(i);    
  173.             // 第四步,創(chuàng)建單元格,并設(shè)置值    
  174.             row.createCell(0).setCellValue(stu.getName());    
  175.             row.createCell(1).setCellValue(stu.getClasses());    
  176.             row.createCell(2).setCellValue(stu.getScore());    
  177.             cell = row.createCell(3);    
  178.             cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getTime()));   
  179.         }            
  180.         //第六步,輸出Excel文件  
  181.         OutputStream output=response.getOutputStream();  
  182.         response.reset();  
  183.         long filename = System.currentTimeMillis();  
  184.         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//設(shè)置日期格式  
  185.         String fileName = df.format(new Date());// new Date()為獲取當(dāng)前系統(tǒng)時間  
  186.         response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");  
  187.         response.setContentType("application/msexcel");          
  188.         wb.write(output);  
  189.         output.close();  
  190.     }   

3.3 導(dǎo)出文件api補(bǔ)充

大家可以看到上面service的代碼只是最基本的導(dǎo)出。

在實際應(yīng)用中導(dǎo)出的Excel文件往往需要閱讀和打印的,這就需要對輸出的Excel文檔進(jìn)行排版和樣式的設(shè)置,主要操作有合并單元格、設(shè)置單元格樣式、設(shè)置字體樣式等。

3.3.1 單元格合并

使用HSSFSheet的addMergedRegion()方法 

  1. public int addMergedRegion(CellRangeAddress region) 

參數(shù)CellRangeAddress 表示合并的區(qū)域,構(gòu)造方法如下:依次表示起始行,截至行,起始列, 截至列 

  1. CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol) 

3.3.2 設(shè)置單元格的行高和列寬 

  1. HSSFSheet sheet=wb.createSheet();  
  2. sheet.setDefaultRowHeightInPoints(10);//設(shè)置缺省列高sheet.setDefaultColumnWidth(20);//設(shè)置缺省列寬  
  3. //設(shè)置指定列的列寬,256 * 50這種寫法是因為width參數(shù)單位是單個字符的256分之一  
  4. sheet.setColumnWidth(cell.getColumnIndex(), 256 * 50); 

3.3.3 設(shè)置單元格樣式

1、創(chuàng)建HSSFCellStyle 

  1. HSSFCellStyle cellStyle=wkb.createCellStyle() 

2、設(shè)置樣式 

  1. // 設(shè)置單元格的橫向和縱向?qū)R方式,具體參數(shù)就不列了,參考HSSFCellStyle  
  2.   cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);  
  3.   cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  4.   /* 設(shè)置單元格的填充方式,以及前景顏色和背景顏色  
  5.    三點注意:  
  6.    1.如果需要前景顏色或背景顏色,一定要指定填充方式,兩者順序無所謂;  
  7.    2.如果同時存在前景顏色和背景顏色,前景顏色的設(shè)置要寫在前面;  
  8.    3.前景顏色不是字體顏色。  
  9.   */  
  10.   //設(shè)置填充方式(填充圖案)  
  11.   cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);  
  12.   //設(shè)置前景色  
  13.   cellStyle.setFillForegroundColor(HSSFColor.RED.index);  
  14.   //設(shè)置背景顏色  
  15.   cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index);  
  16.   // 設(shè)置單元格底部的邊框及其樣式和顏色  
  17.   // 這里僅設(shè)置了底邊邊框,左邊框、右邊框和頂邊框同理可設(shè)  
  18.   cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);  
  19.   cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);  
  20.   //設(shè)置日期型數(shù)據(jù)的顯示樣式  
  21.   cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); 

3、將樣式應(yīng)用于單元格 

  1. cell.setCellStyle(cellStyle);  
  2.   //將樣式應(yīng)用到行,但有些樣式只對單元格起作用  
  3.   row.setRowStyle(cellStyle); 

3.3.4設(shè)置字體樣式

1、創(chuàng)建HSSFFont對象(調(diào)用HSSFWorkbook 的createFont方法) 

  1. HSSFWorkbook wb=new HSSFWorkbook();  
  2. HSSFFont  fontStyle=wb.createFont();  
  3. HSSFWorkbook wb=new HSSFWorkbook (); 

2、設(shè)置字體各種樣式 

  1. //設(shè)置字體樣式  
  2.   fontStyle.setFontName("宋體");    
  3.   //設(shè)置字體高度  
  4.   fontStyle.setFontHeightInPoints((short)20);    
  5.   //設(shè)置字體顏色  
  6.   font.setColor(HSSFColor.BLUE.index);  
  7.   //設(shè)置粗體  
  8.   fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  9.   //設(shè)置斜體  
  10.   font.setItalic(true);  
  11.   //設(shè)置下劃線  
  12.   font.setUnderline(HSSFFont.U_SINGLE); 

3、將字體設(shè)置到單元格樣式 

  1. //字體也是單元格格式的一部分,所以從屬于HSSFCellStyle  
  2. // 將字體對象賦值給單元格樣式對象  
  3. cellStyle.setFont(font);  
  4. // 將單元格樣式應(yīng)用于單元格  
  5. cell.setCellStyle(cellStyle); 

大家可以看出用poi導(dǎo)出文件還是比較麻煩的,等下次在為大家介紹下irport的方法。

導(dǎo)出的api基本上就是這些,最后也希望上文對大家能有所幫助。   

 

責(zé)任編輯:龐桂玉 來源: Java知音
相關(guān)推薦

2020-12-18 10:40:00

ExcelJava代碼

2022-10-12 09:55:14

xls文件xlsx文件

2010-05-26 17:12:52

2012-12-21 16:13:36

Outlook 201

2020-09-11 09:23:42

文件重命名Linux字符串

2023-09-20 10:04:04

Python工具

2012-09-05 09:34:13

AD域導(dǎo)入導(dǎo)出帳號

2024-06-19 10:53:45

2010-11-24 11:13:07

MySQL批量導(dǎo)入

2009-12-04 16:49:33

PHP批量導(dǎo)出csv文

2024-07-03 11:08:43

2024-09-13 15:20:46

2024-12-02 14:48:30

Docker鏡像文件

2011-05-16 14:17:31

MySQL導(dǎo)入導(dǎo)出大量數(shù)據(jù)

2022-04-28 10:46:16

腳手架前端vue

2010-05-24 17:20:07

MySQL導(dǎo)入

2010-11-03 10:26:22

DB2存儲過程

2010-06-09 10:09:39

MySQL 數(shù)據(jù)庫導(dǎo)入

2010-07-23 09:25:50

SQL Server導(dǎo)

2024-06-17 12:25:49

點贊
收藏

51CTO技術(shù)棧公眾號