Java e EasyExcel implementam importação e exportação de arquivos, importar e exportar é muito simples
Tags relacionadas:1. Entendendo a Coleta de lixo em Java
2. O design inteligente do Java Map
Introdução ao Java e EasyExcel:
O projeto precisa importar e exportar arquivos Excel e fazer o download deles. Por exemplo, importar informações de funcionários, exportar informações de funcionários e a entrada manual são tarefas trabalhosas, então esta postagem do blog ensina como importar e exportar arquivos Excel em Java.
pilha de tecnologias
Ferramenta Excel: EasyExcel
Framework selecionado: Spring, Spring MVC, MyBatis (SSM)
Ferramenta de gerenciamento de build do projeto: Maven
requisitos:
1.É necessário usar a ferramenta Excel para realizar a importação e exportação de informações de funcionários
2.O requisito de exportação é gerar o arquivo no local especificado e fazer o download
3.Após a importação do arquivo, os dados são armazenados no banco de dados e exibidos na página
4.Exportar o arquivo: clicar em Exportar, gravar no endereço especificado e fazer o download do arquivo
Resultados com Java e EasyExcel
Estrutura do projeto
Código-fonte principal
Importar dependências do Alibaba EasyExcel
< dependency >
< groupId > com.alibaba
< artifactId > easyexcel
< version > 2.1.6
EasyExcel é usado aqui, por que não POI?
Porque EasyExcel é uma evolução do POI, o POI é relativamente pesado e o EasyExcel removeu alguns aspectos complicados do POI, tornando-o mais leve, por isso este artigo usa EasyExcel
EasyExcel é um produto da Alibaba, POI é um produto de código aberto da Apache
Foundation, EasyExcel fez uma evolução do POI
Classe de entidade principal

package com.wanshi.spring.entity ; _
import com.alibaba.excel.annotation.ExcelIgnore ; _
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@ExcelIgnore _
private String noid ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Name" )
private String emp_name ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Age" )
private Integer emp_age ;
@ExcelIgnore _
private Integer emp_sex ;
// redundant fields
@ColumnWidth ( 20 ) _
@ExcelProperty ( " employee gender" )
private String str_emp_sex ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( "Employee Salary " )
private Double emp_salary ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Address" )
private String emp_address ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( "EmployeePosition " )
private String emp_position ;
/ / Paging related, the current page and the number of data per page
@ExcelIgnore _
private Integer pageNum ;
@ExcelIgnore _
private Integer pageSize ;
}
Classe listener principal
Classe EmployeeListener:
package com.wanshi.spring.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wanshi.spring.entity.Employee;
import java.util.ArrayList;
import java.util.List;
public class EmployeeReadListener extends AnalysisEventListener < Employee > {
// employee collection
private static List employeeList = new ArrayList < >( );
// Each time the read is the same, the invoke method will be called once
@Override
public void invoke ( Employee data, AnalysisContext context) {
employeeList.add (data);
System.out.println ( "Parse to a piece of data: " + data);
}
// After reading all, this method will be called
@Override
public void doAfterAllAnalysed ( AnalysisContext context) {
System.out.println ( "All parsing completed" );
}
/**
* Return the read employee collection
* @return
*/
public static List getStudentList ( ) {
return employeeList ;
}
}
2. O design inteligente do Java Map
Introdução ao Java e EasyExcel:
O projeto precisa importar e exportar arquivos Excel e fazer o download deles. Por exemplo, importar informações de funcionários, exportar informações de funcionários e a entrada manual são tarefas trabalhosas, então esta postagem do blog ensina como importar e exportar arquivos Excel em Java.
pilha de tecnologias
Ferramenta Excel: EasyExcel
Framework selecionado: Spring, Spring MVC, MyBatis (SSM)
Ferramenta de gerenciamento de build do projeto: Maven
requisitos:
1.É necessário usar a ferramenta Excel para realizar a importação e exportação de informações de funcionários
2.O requisito de exportação é gerar o arquivo no local especificado e fazer o download
3.Após a importação do arquivo, os dados são armazenados no banco de dados e exibidos na página
4.Exportar o arquivo: clicar em Exportar, gravar no endereço especificado e fazer o download do arquivo
Resultados com Java e EasyExcel
Estrutura do projeto
Código-fonte principal
Importar dependências do Alibaba EasyExcel
< dependency >
< groupId > com.alibaba
< artifactId > easyexcel
< version > 2.1.6
EasyExcel é usado aqui, por que não POI?
Porque EasyExcel é uma evolução do POI, o POI é relativamente pesado e o EasyExcel removeu alguns aspectos complicados do POI, tornando-o mais leve, por isso este artigo usa EasyExcel
EasyExcel é um produto da Alibaba, POI é um produto de código aberto da Apache
Foundation, EasyExcel fez uma evolução do POI
Classe de entidade principal

package com.wanshi.spring.entity ; _
import com.alibaba.excel.annotation.ExcelIgnore ; _
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@ExcelIgnore _
private String noid ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Name" )
private String emp_name ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Age" )
private Integer emp_age ;
@ExcelIgnore _
private Integer emp_sex ;
// redundant fields
@ColumnWidth ( 20 ) _
@ExcelProperty ( " employee gender" )
private String str_emp_sex ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( "Employee Salary " )
private Double emp_salary ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( " Employee Address" )
private String emp_address ;
@ColumnWidth ( 20 ) _
@ExcelProperty ( "EmployeePosition " )
private String emp_position ;
/ / Paging related, the current page and the number of data per page
@ExcelIgnore _
private Integer pageNum ;
@ExcelIgnore _
private Integer pageSize ;
}
Classe listener principal
Classe EmployeeListener:
package com.wanshi.spring.listener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wanshi.spring.entity.Employee;
import java.util.ArrayList;
import java.util.List;
public class EmployeeReadListener extends AnalysisEventListener < Employee > {
// employee collection
private static List
// Each time the read is the same, the invoke method will be called once
@Override
public void invoke ( Employee data, AnalysisContext context) {
employeeList.add (data);
System.out.println ( "Parse to a piece of data: " + data);
}
// After reading all, this method will be called
@Override
public void doAfterAllAnalysed ( AnalysisContext context) {
System.out.println ( "All parsing completed" );
}
/**
* Return the read employee collection
* @return
*/
public static List
return employeeList ;
}
}
Java+EasyExcel Importação de arquivo com EasyExcel
Java+EasyExcel, classe de teste Test: implementação da importação de arquivo e armazenamento no banco de dados
@Test
public void test1 () {
ExcelReaderBuilder workBook = EasyExcel.read
( "C:\Users\wanghuicall\Desktop\employee.xlsx" , Employee . class , new EmployeeReadListener ()) ;
// wrapping the worksheet
ExcelReaderSheetBuilder sheet1 = workBook.sheet ();
// read
sheet1.doRead();
//write to database
List
for (Employee employee : studentList ) {
employee.setNoid ( PbSecretUtils.uuid ());
employeeMapper.insert (employee);
}
}
Clique na página para importar o arquivo e salvá-lo no banco de dados
Classe EmployeeController:
@PostMapping ( " / import_employee_excel " )
public String importEmployeeExcel ( MultipartFile emp_excel ) {
employeeService.importExcel ( emp_excel );
return "redirect:/employee/list" ;
}
Classe EmployeeService:
/**
* Get the file selected by the user and save the file to the specified location and then save the data to the database
* @param emp_excel
* @return
*/
public Integer importExcel(MultipartFile emp_excel) {
try {
String fileName = FileUploadUtil.upload(emp_excel, "");
ExcelReaderBuilder workBook = EasyExcel.read
(GlobalSet.upload_url+fileName, Employee.class, new EmployeeReadListener());
// å°è£å·¥ä½è¡¨
ExcelReaderSheetBuilder sheet1 = workBook.sheet();
// 读å
sheet1.doRead();
List
for (Employee employee : studentList) {
employee.setNoid(PbSecretUtils.uuid());
if ("ç".equals(employee.getStr_emp_sex())) {
employee.setEmp_sex(1);
} else {
employee.setEmp_sex(2);
}
employeeMapper.insert (employee);
}
} catch ( IOException e) {
e.printStackTrace ();
}
return 0 ;
}
Java+EasyExcel Exportação de arquivo com EasyExcel
Classe de teste Test: exportar arquivo para o local especificado
@Test
public void test2 () throws FileNotFoundException {
List
ExcelWriterBuilder workBook = EasyExcel.write ( GlobalSet.download_url , Employee . class ) ;
// sheet method parameters: the sequence number of the worksheet (starting from 0) or the name of the worksheet
workBook.sheet ( "Test Data Sheet" ). doWrite ( employeeList );
System.out.println ( "Write complete!" );
}
/**
* Generate test data
* @return
*/
public List
List
for (int i = 1; i < 100; i++) {
Employee employee = new Employee();
employee.setEmp_name("å°ç®è¯ï¼"+i);
employee.setEmp_age(19);
if (i % 10 == 0) {
employee.setEmp_sex(1);
} else {
employee.setEmp_sex(2);
}
employee.setEmp_salary(19999.00+i);
employee.setEmp_address ( "Beijing Chaoyang District" + i );
employee.setEmp_position ( "Java Senior Engineer" );
employeeList.add (employee);
}
return employeeList ;
}
Após exportar para o arquivo especificado pela página e fazer o download do arquivo
Classe EmployeeController
@GetMapping ( " / export_employee_excel " )
public void exportEmployeeExcel(HttpServletResponse response) {
try {
employeeService.exportEmployeeExcel(response);
} catch (IOException e) {
e.printStackTrace();
}
}
Classe EmployeeServiceï¼
public void exportEmployeeExcel(HttpServletResponse response) throws IOException {
List
try {
ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
// sheet method parameters: the sequence number of the worksheet (starting from 0) or the name of the worksheet
workBook.sheet ( "Employee Information" ). doWrite ( kspwStudentSeatList );
downloadTempalate (response);
System.out.println ( "Write complete!" );
} catch (Exception e) {
e.printStackTrace ();
}
}
/**
* download file
* @param response
* @throws IOException
*/
public static void downloadTempalate ( HttpServletResponse response) throws IOException {
// Tell the browser what software to use to open this file
response.setHeader ( "content-Type" , "application/vnd.ms-excel" );
// default name of the downloaded file
response.setHeader ( "Content-Disposition" , " attachment;filename =" + URLEncoder.encode ( "Employee Information.xlsx" , "utf-8" ));
//4. Create input and output streams
FileInputStream input = new FileInputStream ( GlobalSet.download_url );
ServletOutputStream sos = response.getOutputStream ();
//IO stream gets the byte stream of the file, and then responds to the browser
byte [ ] arr = new byte [ 1024 ];
int res = 0 ;
while ( (res = input.read ( arr )) > 0 ){
// output the read content to the output stream
sos.write ( arr , 0 , res);
}
input.close ();
sos.close ();
}
Artigos relacionados
-
6 tecnologias opcionais para armazenamento de dados
Equipe da Base de conhecimento
Explorar mais ofertas especiais
-
Short Message Service (SMS) e Serviço de e-mail
Pacote de 50.000 e-mails a partir de US$ 1,99, 120 mensagens curtas a partir de apenas US$ 1,00
