java导出文件到excel文件怎么打开_java实现文件导入导出到Excel

本文介绍了Java实现文件导入导出到Excel的操作步骤和功能实现原理,涉及的组件包括jquery-EasyUI、commons-fileupload、poi等。导入过程包括上传文件、解析Excel并保存到数据库,导出则借助table2excel组件。详细讲解了各个功能的实现细节和代码示例。
摘要由CSDN通过智能技术生成

1.导入导出功能操作步骤

导入:"下载导入模板" -->保存文件到本地-->在模板中输入要导入的数据行-->"导入"-->选择录入数据的模板文件-->"确定"

导出:"导出"-->保存Excel文件到本地。

2.功能实现原理

2.1.外部组件依赖说明

(1)数据库访问相关:mysql-connector-jaca-5.0.8-bin.jar

c3p0-0.9.1.2.jar

commons-dbutils-1.4.jar

commons-io-2.6.jar

commons-logging-1.1.1.jar

(2)前端jsp页面jstl相关:jstl.jar

standard.jar

(3)导入功能相关:jquery-EasyUI(前端组件)

commons-fileupload.jar

poi-3.17.jar

poi-ooxml-3.17.jar

poi-ooxml-schemas-3.17.jar

xmlbeans-2.6.0.jar

commons-collections4-4.1.jar

commons-beanutils-1.8.0.jar

slf4j-api-1.7.5.jar

(4)导出功能相关:jquery-table2excel(前端组件)

如果是maven工程,pom相关依赖:

org.apache.poi

poi

3.17

org.apache.poi

poi-ooxml

3.17

commons-collections4

commons-collections4

4.1

commons-beanutils

commons-beanutils

1.8.3

org.slf4j

slf4j-api

1.7.5

2.2.功能实现原理说明:

(1)导入:利用jquery-EasyUI组件展示上传文件对话框,选择目标excel文件;利用commons-fileupload组件解析和处理前端传递过来

的excel文件流数据;利用poi组件解析excel文件内容,转换成数据库表对象结构,利用c3p0、dbutils组件保存到数据库表中。

(2)导出:利用table2excel组件导出表格内容到目标excel文件。

3.功能实现步骤

(1)拷贝需要引入的依赖组件包和util包下的工具类代码到工程中。

(2)在需要导入导出的目标库表对象类中,将excel文件相关的几个字段属性,增加"@ExcelCell"注解。参考(Product.java)。

注意:类中属性的数据类型只能为包装类型(如String,Double等,不包含Integer),不能为基本类型(int,double等)。

index属性值必须与excel文件中的数据记录顺序一致。

(3)根据对象类结构,创建和上传导入模板文件到服务器文件夹,参考(WEB-INF/template/product.xlsx),

修改DownloadImportTemplateServlet里对应的文件名。

(4)增加导入excel功能代码,参考(ProductService.java中importProductDataFromExcel方法)。

(5)增加导出功能代码,参考(pagination.jsp中export2Excel方法)。

下面是前端页面pageination.jsp代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

Insert title here

var options={

type:'post',

url:'importExcelData',

dataType:'json',

success: function (json) {

alert(json.message);

location.reload();

},

error: function() {

alert("error");

}

};

$('#uploadfile-form').ajaxSubmit(options);

$('#import-dialog').dialog('close');

}

function export2Excel() {

$("#table").table2excel({//exclude CSS class

exclude: ".noExl",

sheetName:"product",

filename:"product.xls"});

}

序号名称价格分类库存数量
${vs.count}${product.name}${product.price}${product.category}${product.pnum}
选择文件:

View Code

实体类Product.java代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagegraduation.sample.entity;importgraduation.sample.util.excel.ExcelCell;public classProduct {privateString id;

@ExcelCell(index= 2)privateString name;

@ExcelCell(index= 3)privateDouble price;

@ExcelCell(index= 4)privateString category;publicDouble getPnum() {returnpnum;

}public voidsetPnum(Double pnum) {this.pnum =pnum;

}

@ExcelCell(index= 5)privateDouble pnum;publicString getId() {returnid;

}public voidsetId(String id) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public doublegetPrice() {returnprice;

}public void setPrice(doubleprice) {this.price =price;

}publicString getCategory() {returncategory;

}public voidsetCategory(String category) {this.category =category;

}

}

View Code

模板下载DownloadImportTemplateServlet代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagegraduation.sample.servlet;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.URLEncoder;

@WebServlet("/DownloadImportTemplate")public class DownloadImportTemplateServlet extendsHttpServlet {private static final String FILE_PATH = "/WEB-INF/template/";private static final String FILE_NAME = "product.xlsx";private static final long serialVersionUID = 1L;public voiddoGet(HttpServletRequest request, HttpServletResponse

response)throwsServletException, IOException {//设置ContentType字段值

response.setContentType("text/html;charset=utf-8");//设置相应消息编码

response.setCharacterEncoding("utf-8");//设置请求消息编码

request.setCharacterEncoding("utf-8");//获取所要下载的文件名称//对文件名称编码

String filename = new String(FILE_NAME.trim().getBytes("iso8859-1"), "UTF-8");//通知浏览器以下载的方式打开

response.addHeader("Content-Type", "application/octet-stream");

response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(filename, "utf-8"));//通过文件流读取文件

InputStream in = getServletContext().getResourceAsStream(FILE_PATH +FILE_NAME);//获取response对象的输出流

OutputStream out =response.getOutputStream();byte[] buffer = new byte[1024];intlen;//循环取出流中的数据

while ((len = in.read(buffer)) != -1) {

out.write(buffer,0, len);

}

}public voiddoPost(HttpServletRequest request, HttpServletResponse

response)throwsServletException, IOException {

doGet(request, response);

}

}

View Code

导入到Excel,ImportExcelDataServlet代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagegraduation.sample.servlet;importgraduation.sample.service.ProductService;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;import java.io.*;/*** 导入Excel文件内容到数据库表实现步骤:

* 1.接收上传的文件输入流

* 2.将文件内容拷贝到 WEB-INF/upload文件夹下

* 3.解析WEB-INF/upload下对应的文件内容,保存至数据库表*/@WebServlet("/importExcelData")public class ImportExcelDataServlet extendsHttpServlet {

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {this.doGet(req, resp);

}

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

resp.setContentType("text/json;charset=UTF-8");

resp.setCharacterEncoding("UTF-8");

PrintWriter out=resp.getWriter();

String str= "{\"code\":\"0\",\"message\":\"success\"}";try{

ProductService productService= newProductService();boolean result =productService.importProductDataFromExcel(req);if (!result) {

str= "{\"code\":\"-1\",\"message\":\"failed\"}";

}

}catch(Exception e) {

e.printStackTrace();

str= "{\"code\":\"-2\",\"message\":\"error\"}";

}//返回响应结果到前端页面

out.println(str);

out.flush();

out.close();

}

}

View Code

service层代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagegraduation.sample.service;importgraduation.sample.dao.ProductDao;importgraduation.sample.dao.ProductDaoImpl;importgraduation.sample.util.FileUploadFormParam;importgraduation.sample.entity.PageBean;importgraduation.sample.entity.Product;importgraduation.sample.util.FileUploadRequestUtil;importgraduation.sample.util.excel.ExcelLogs;importgraduation.sample.util.excel.ExcelUtil;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.servlet.ServletFileUpload;importjavax.servlet.http.HttpServletRequest;import java.io.*;importjava.sql.SQLException;importjava.util.Collection;importjava.util.List;importjava.util.UUID;public classProductService {public PageBean findProductByPage(int currentPage, int currentCount) throwsSQLException {

PageBean pageBean= newPageBean();

pageBean.setCurrentPage(currentPage);

pageBean.setCurrentCount(currentCount);

ProductDaoImpl imp= newProductDaoImpl();

List products =imp.findByProductPage(currentCount, currentPage);

pageBean.setPs(products);int totalCount =imp.findProductCount();

pageBean.setTotalCount(totalCount);int totalPage = (int) Math.ceil(totalCount * 1.0 /currentCount);

pageBean.setTotalPage(totalPage);returnpageBean;

}public boolean importProductDataFromExcel(HttpServletRequest request) throwsIOException, SQLException {//判断表单属性enctype,值是否为"multipart/form-data"

if (!ServletFileUpload.isMultipartContent(request)) {return false;

}//调用工具类解析请求参数

FileUploadFormParam formParam =FileUploadRequestUtil.parseParam(request);//获取请求参数中的file类型的item值

FileItem fileItem = formParam.getFileMap().get("UPLOAD_FILE");if (fileItem == null) {return false;

}//解析file类型的item内容值,生成文件保存在服务器upload文件夹中

String filePath = this.uploadFile(request, fileItem);//将保存到服务器的文件内容解析,导入到数据库表tv_product中

File file = newFile(filePath);

InputStream inputStream= newFileInputStream(file);

ExcelLogs logs= newExcelLogs();//将上传到服务器的文件内容加载解析

Collection importExcel = ExcelUtil.importExcel(Product.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);//文件解析内容保存到数据库表

ProductDao productDao = newProductDaoImpl();for(Product p : importExcel) {try{

productDao.addProduct(p);

}catch(SQLException e) {//TODO:

e.printStackTrace();throwe;

}

}return true;

}/*** 上传文件到服务器指定路径

*

*@paramfileItem

*@return文件保存路径

*@throwsIOException*/

private String uploadFile(HttpServletRequest request, FileItem fileItem) throwsIOException {

String filePath= null;//上传的完整文件路径名

String uploadFilePath =fileItem.getName();if (uploadFilePath == null || uploadFilePath.equals("")) {returnfilePath;

}//获取文件名

String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf("\\") + 1);//保存到服务器上的文件名

String fileName = new StringBuffer(UUID.randomUUID().toString().replace("-", ""))

.append("_").append(uploadFileName).toString();//保存到服务器上的文件路径

filePath = request.getServletContext().getRealPath("/WEB-INF/upload/" +fileName);//读取和写入文件内容

InputStream in = null;

FileOutputStream out= null;try{

File file= newFile(filePath);

file.getParentFile().mkdirs();

file.createNewFile();//输入流

in =fileItem.getInputStream();//输出流

out = newFileOutputStream(file);//流的对拷

byte[] buffer = new byte[1024];//每次读取1个字节

intlen;//开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中

while ((len = in.read(buffer)) > 0) {

out.write(buffer,0, len);

}

}catch(Exception e) {

e.printStackTrace();throwe;

}finally{//关闭文件输入输出流

if (in != null) {

in.close();

}if (out != null) {

out.close();

}

}returnfilePath;

}

}

View Code

导出功能代码:

$("#table").table2excel({//exclude CSS class

exclude: ".noExl",

sheetName:"product",

filename:"product.xls"});

4.table2excel插件介绍

jquery-table2excel是一款可以将HTML表格的内容导出到微软Excel电子表格中的jQuery插件。该插件可以根据你的需要导出表格中的内容,不需要的行可以不导出。 它文件体积小,使用非常方便。

先写好前端按钮,还需要一个table

内容内容内容

初始化js

function Export(){

$("#exceltable").table2excel({ //exceltable为存放数据的table

//不被导出的表格行的CSS class类

exclude: ".noExl",//导出的Excel文档的名称

name: "表格-" + newDate().getTime(),//Excel文件的名称

filename: "表格-" + new Date().getTime() + ".xls",

bootstrap:false});

}

table2excel插件的可用配置参数有:

exclude:不被导出的表格行的CSS class类。

name:导出的Excel文档的名称。

filename:Excel文件的名称。

exclude_img:是否导出图片。

exclude_links:是否导出超链接

exclude_inputs:是否导出输入框中的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值