I'm here to slap my face! Who said Java can't batch import and export with files?

1 Introduction

The import and export database of Java implementation files is currently a relatively common function in most systems. Today, I will write a small demo to understand its principle. Students who have not been exposed to it can also look at it for reference.

At present, the import and export technologies I have come into contact with mainly include POI and iReport. Poi is mainly used as some data to be imported into the database in batches, and iReport is used for report export. In addition, there is a method similar to poi in jxl, but it seems that it has not been updated for a long time. Office after 2007 does not seem to support it, so I will not talk about it here.

2. Detailed explanation of POI use

2.1 What is Apache POI?

Apache POI is an open source library of the Apache Software Foundation. POI provides an API for Java programs to read and write Microsoft Office format files.

2.2 POI jar package import

This tutorial uses the maven project, and the jar package version uses poi-3.14 and poi-ooxml-3.14. The latest version is 3.16. Because the related APIs have been updated after 3.15, some operations may be different, please pay attention.


11561958-8d2c5fc15ca21a8f.png
image.png

2.3 API explanation of POI

2.3.1 Structure

HSSF - Provides the ability to read and write files in Microsoft Excel format.
XSSF - Provides the ability to read and write files in Microsoft Excel OOXML format.
HWPF - Provides the ability to read and write files in Microsoft Word format.
HSLF - Provides the ability to read and write files in Microsoft PowerPoint format.
HDGF - Provides the ability to read and write files in Microsoft Visio format.
2.3.2 Objects

This article mainly introduces two components, HSSF and XSSF. Simply speaking, HSSF is used to operate the excel.xls file before the Office 2007 version, and XSSF is used to operate the excel.xlsx file after the Office 2007 version. Note that the suffixes of the two are different.

HSSF is in the org.apache.poi.hssf.usermodel package. It implements the Workbook interface for .xls format in Excel files

Common components:

HSSFWorkbook : excel document object
HSSFSheet : excel form
HSSFRow : excel row
HSSFCell : excel grid cell HSSFFont
: excel font HSSFDataFormat :
date format


HSSFCellStyle : cell style
auxiliary operations include:

HSSFDateUtil : Date
HSSFPrintSetup : Print
HSSFErrorConstants : Error information table
XSSF is in org.apache.xssf.usemodel package and implements Workbook interface for .xlsx format in Excel file

Common components:

XSSFWorkbook : excel document object
XSSFSheet: excel form
XSSFRow: excel row
XSSFCell: excel grid cell
XSSFFont: excel font
XSSFDataFormat : date format
similar to HSSF;

2.3.3 Description of field types common to both components

In fact, the two components are two formats for excel, and most of the operations are the same.


11561958-cd27186dd45179f5.png
image.png

2.3.4 Operation steps

Taking HSSF as an example, XSSF operates the same.

First, understand the organization of an Excel file. An Excel file corresponds to a workbook (HSSFWorkbook). A workbook can be composed of multiple sheets (HSSFSheet). A sheet is composed of multiple rows (HSSFRow). A row is It consists of multiple cells (HSSFCell).

1. Open or create an "Excel file object" with HSSFWorkbook

2. Use the HSSFWorkbook object to return or create a Sheet object

3. Use the Sheet object to return the row object, and use the row object to get the Cell object

4. Read and write to the Cell object.

3. Code operation

3.1 Rendering

Convention, look at the renderings before posting the code

Excel files in one of two formats:


11561958-5aca2942ee16dcfb.png
image.png

11561958-7fc2fb5f091c480f.png
image.png

Code structure:


11561958-bd6c3e3863f0b2d0.png
image.png

After importing: (I imported it twice, without checking)
11561958-d66f5812d3215190.png
image.png

Export effect:
11561958-adf28f2402c0045c.png
image.png

3.2 Code details

Here I am based on Spring+SpringMVC+Mybatis

Controller:

package com.allan.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.formula.functions.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.allan.pojo.Student;
import com.allan.service.StudentService;
/**

  • @author The grandfather of the small shop

/
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
/
*
* Batch import form data
*
* @param request
* @param myfile
* @return
*/

@RequestMapping(value="/importExcel",method=RequestMethod.POST)    
public String importExcel(@RequestParam("myfile") MultipartFile myFile) {    
    ModelAndView modelAndView = new ModelAndView();    
    try {    
        Integer num = studentService.importExcel(myFile);    
    } catch (Exception e) {    
        modelAndView.addObject("msg", e.getMessage());    
        return "index";    
    }    
    modelAndView.addObject("msg", "数据导入成功");    

    return "index";    
}    

@RequestMapping(value="/exportExcel",method=RequestMethod.GET)    
public void exportExcel(HttpServletResponse response) {        
    try {    
        studentService.exportExcel(response);    
    } catch (Exception e) {    
        e.printStackTrace();    
    }    
}    

}
Service

package com.allan.service.impl;

import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.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.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.allan.mapper.StudentMapper;
import com.allan.pojo.Student;
import com.allan.service.StudentService;
/**

  • @author The grandfather of the small shop

/
@Service
public class StudentServiceImpl implements StudentService{
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
@Autowired
private StudentMapper studentMapper;
/
*
* Import Excel, compatible with xls and xlsx
*/
@SuppressWarnings( "resource")
public Integer importExcel(MultipartFile myFile) throws Exception {
// 1. Use HSSFWorkbook to open or create "Excel file object"
//
// 2. Use HSSFWorkbook object to return or create Sheet object
//
// 3. Use Sheet The object returns the row object, and the row object is used to get the Cell object
//
// 4. Read and write to the Cell object.
//Get the file name
Workbook workbook = null ;
String fileName = myFile.getOriginalFilename();
if(fileName.endsWith(XLS)){
//2003
workbook = new HSSFWorkbook(myFile.getInputStream());
}else if(fileName.endsWith(XLSX)){
//2007
workbook = new XSSFWorkbook(myFile.getInputStream());
}else{
throw new Exception("文件不是Excel文件");
}

    Sheet sheet = workbook.getSheet("Sheet1");    
    int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+    
    if(rows==0){    
        throw new Exception("请填写数据");    
    }    
    for (int i = 1; i <= rows+1; i++) {    
        // 读取左上端单元格    
        Row row = sheet.getRow(i);    
        // 行不为空    
        if (row != null) {    
            // **读取cell**    
            Student student = new Student();    
            //姓名    
            String name = getCellValue(row.getCell(0));    
            student.setName(name);    
            //班级    
            String classes = getCellValue(row.getCell(1));    
            student.setClasses(classes);    
            //分数    
            String scoreString = getCellValue(row.getCell(2));    
            if (!StringUtils.isEmpty(scoreString)) {    
                Integer score = Integer.parseInt(scoreString);    
                student.setScore(score);    
            }    
            //考试时间    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟      
            String dateString = getCellValue(row.getCell(3));      
            if (!StringUtils.isEmpty(dateString)) {    
                Date date=sdf.parse(dateString);      
                student.setTime(date);    
            }    
            studentMapper.insert(student);    
        }    
    }    
    return rows-1;    
}    

/**    
 * 获得Cell内容    
 *     
 * @param cell    
 * @return    
 */    
public String getCellValue(Cell cell) {    
    String value = "";    
    if (cell != null) {    
        // 以下是判断数据的类型    
        switch (cell.getCellType()) {    
        case HSSFCell.CELL_TYPE_NUMERIC: // 数字    
            value = cell.getNumericCellValue() + "";    
            if (HSSFDateUtil.isCellDateFormatted(cell)) {    
                Date date = cell.getDateCellValue();    
                if (date != null) {    
                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);    
                } else {    
                    value = "";    
                }    
            } else {    
                value = new DecimalFormat("0").format(cell.getNumericCellValue());    
            }    
            break;    
        case HSSFCell.CELL_TYPE_STRING: // 字符串    
            value = cell.getStringCellValue();    
            break;    
        case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean    
            value = cell.getBooleanCellValue() + "";    
            break;    
        case HSSFCell.CELL_TYPE_FORMULA: // 公式    
            value = cell.getCellFormula() + "";    
            break;    
        case HSSFCell.CELL_TYPE_BLANK: // 空值    
            value = "";    
            break;    
        case HSSFCell.CELL_TYPE_ERROR: // 故障    
            value = "非法字符";    
            break;    
        default:    
            value = "未知类型";    
            break;    
        }    
    }    
    return value.trim();    
}    
/**    
 * 导出excel文件    
 */    
public void exportExcel(HttpServletResponse response) throws Exception {    
    // 第一步,创建一个webbook,对应一个Excel文件      
    HSSFWorkbook wb = new HSSFWorkbook();      
    // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet      
    HSSFSheet sheet = wb.createSheet("Sheet1");      
    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short      
    HSSFRow row = sheet.createRow(0);      
    // 第四步,创建单元格,并设置值表头 设置表头居中      
    HSSFCellStyle style = wb.createCellStyle();      
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式      

    HSSFCell cell = row.createCell(0);    
    cell.setCellValue("姓名");      
    cell.setCellStyle(style);      
    cell = row.createCell(1);      
    cell.setCellValue("班级");      
    cell.setCellStyle(style);      
    cell = row.createCell(2);      
    cell.setCellValue("分数");      
    cell.setCellStyle(style);      
    cell = row.createCell(3);      
    cell.setCellValue("时间");      
    cell.setCellStyle(style);      

    // 第五步,写入实体数据 实际应用中这些数据从数据库得到,      
    List<Student> list = studentMapper.selectAll();      

    for (int i = 0; i < list.size(); i++){      
        row = sheet.createRow(i + 1);      
        Student stu = list.get(i);      
        // 第四步,创建单元格,并设置值      
        row.createCell(0).setCellValue(stu.getName());      
        row.createCell(1).setCellValue(stu.getClasses());      
        row.createCell(2).setCellValue(stu.getScore());      
        cell = row.createCell(3);      
        cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(stu.getTime()));      
    }              
    //第六步,输出Excel文件    
    OutputStream output=response.getOutputStream();    
    response.reset();    
    long filename = System.currentTimeMillis();    
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式    
    String fileName = df.format(new Date());// new Date()为获取当前系统时间    
    response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");    
    response.setContentType("application/msexcel");            
    wb.write(output);    
    output.close();    
}      

}
3.3 Export file api supplement

You can see that the code for the service above is just the most basic export.

In practical applications, the exported Excel files often need to be read and printed, which requires typesetting and style settings for the output Excel documents. The main operations include merging cells, setting cell styles, and setting font styles.

3.3.1 Cell Merge

Use the addMergedRegion() method of HSSFSheet

public int addMergedRegion(CellRangeAddress region)
The parameter CellRangeAddress represents the merged region. The construction method is as follows: the starting row, the ending row, the starting column, and the ending column in order

CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol)
3.3.2 Set the row height and column width of the cell

HSSFSheet sheet=wb.createSheet();
sheet.setDefaultRowHeightInPoints(10);//Set the default column height sheet.setDefaultColumnWidth(20);//Set the default column width
//Set the column width of the specified column, 256 * 50 this This is because the width parameter unit is 1/256 of a single character
sheet.setColumnWidth(cell.getColumnIndex(), 256 * 50);
3.3.3 Set the cell style

1. Create HSSFCellStyle

HSSFCellStyle cellStyle=wkb.createCellStyle()
2. Set the style

// Set the horizontal and vertical alignment of the cell, the specific parameters are not listed, refer to HSSFCellStyle
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
/* Set the filling method and foreground of the cell Color and background color
Three points:
1. If you need foreground color or background color, you must specify the filling method, the order of the two does not matter;
2. If there are both foreground color and background color, the setting of foreground color should be written in front;
3 .Foreground color is not font color.
*/
//Set the fill pattern (fill pattern)
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS);
//Set the foreground color
cellStyle.setFillForegroundColor(HSSFColor.RED.index);
//Set the background color
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index );
// Set the border at the bottom of the cell and its style and color
// Only the bottom border is set here, and the left border, right border and top border can be set similarly to
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT);
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index);
//Set the display style of date data
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
3. Apply the style to the cell

cell.setCellStyle(cellStyle);
//Apply styles to rows, but some styles only work on cells
row.setRowStyle(cellStyle);
3.3.4 Set the font style

1. Create an HSSFFont object (call the createFont method of HSSFWorkbook)

HSSFWorkbook wb=new HSSFWorkbook();
HSSFFont fontStyle=wb.createFont(); HSSFWorkbook
wb=new HSSFWorkbook ();
2. Set various styles of fonts

//Set the font style
fontStyle.setFontName("宋体");
//Set the font height
fontStyle.setFontHeightInPoints((short)20);
//Set the font color
font.setColor(HSSFColor.BLUE.index);
//Set the bold
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//Set italic
font.setItalic(true);
//Set the underline
font.setUnderline(HSSFFont.U_SINGLE);
3. Set the font to the cell style

//The font is also part of the cell format, so it belongs to HSSFCellStyle
// Assign the font object to the cell style object
cellStyle.setFont(font);
// Apply the cell style to the cell
cell.setCellStyle(cellStyle);
everyone It can be seen that it is quite troublesome to export files with poi. I will introduce the method of import next time.

The exported api is basically these, and finally I hope the above can be helpful to everyone.
Pay attention to the editor, and update more dry goods later!

Related Posts