在现在的很多开发中,为了方便很多需求就是把excel的内容通过上传的方式导入到数据库中。接下来主要讲述该功能的开发步骤。
第一部分:导出
(1):在页面中添加 如下代码:
<!-- 导出 -->
<iframe id="dataExportIframe" src="" width="0" height="0" style="display: none"></iframe>
该部分主要是为导出做引子。
在页面中添加导出按钮,如下:
<button class="btn btn-primary" οnclick="exportTaxVva();">导出</button>
由于有引子的存在才利于导出。
(2):在js中设置相应的操作。
//导出
function exportTaxVva(){
//项目的启动地址。
var path=$("#rootpath").val();
//查询条件1
var code = $("#code").val();
//查询条件2
var brief = $("#brief").val();
//执行的完整的url.
var url= path+'/mvc/TaxVva/exportTaxVva?code='+code+"&brief="+brief;
//由于在第一个步骤中已经设置好引子里所以引入。
$("# dataExportIframe").attr("src",url);}
(3):引入相应的jar包,并且将相应的公用代码写好。
引入jar包:
<!-- excel到处 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
写公用的方法,在第四步的时候使用:
package com.seedeer.sdsa.util;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.WritableFont;
import jxl.write.WritableWorkbook;
public class ExcelOperation<T> {
private String serialNumber = "serial"; // 序号标志
/**
* 导出excel
* @param request
* @param response
* @param fileName文件名
* @param fieldTitle
* @param dataField
* @param list
* @throws Exception
*/
public void exportDataExcel(HttpServletRequest request, HttpServletResponse response, String fileName,
String fieldTitle, String dataField, List<T> list) throws Exception {
// 封装response
response.reset();
response.setCharacterEncoding("ISO8859-1");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));// fileChName为下载时用户看到的文件名
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
OutputStream out = response.getOutputStream();
Map<String, Object> map = new HashMap<String, Object>();
String[] title = fieldTitle.split(",");
String[] propery = dataField.split(",");
Integer titleNum = title.length;// Excel中字段的个数
String FileTitle = fileName;// Excel中正文标题
// --建立EXCEL索引、字段名、字段值的关系,存放到map中
for (int i = 0; i < title.length; i++) {
String PojoPropery = propery[i];// grid中title和field是一一对应的,所以可以这么写
String methodName = null;
if (PojoPropery.equals(serialNumber)) {
methodName = PojoPropery;
} else {
String toUpp = PojoPropery.replaceFirst(PojoPropery.substring(0, 1),
PojoPropery.substring(0, 1).toUpperCase());// 把首字母转换为大写
methodName = "get" + toUpp;// 拼成pojo类中getXXX的方法名称
}
map.put(PojoPropery, new ExportExcelColumn(i, title[i], methodName));
}
this.export(out, FileTitle, titleNum, list, map);
}
/**
* 根据用户所选择的字段,动态导出成excel表格(通用方法,调用即可)
*
* @author wudekai os为输出流, title为EXCEL正文标题, titleNum为EXCEL标题字段总数,
* dataList为要导出的数据, map为列索引、标题、数据间的映射关系
*/
public void export(OutputStream os, String title, Integer titleNum, List<T> list, Map<String, Object> map)
throws Exception {
WritableWorkbook wbook = Workbook.createWorkbook(os);// 直接写入内存,不要存放到硬盘中
jxl.write.WritableSheet wsheet = wbook.createSheet("Sheet1", 0);// 定义sheet的名称
jxl.write.WritableFont wfont = null; // 字体
jxl.write.WritableCellFormat wcfFC = null; // 字体格式
jxl.write.Label wlabel = null; // Excel表格的Cell
for (int i = 0; i < titleNum; i++) {
wsheet.setColumnView(i, 20);// 设置列宽
}
// 设置excel标题字体
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
wcfFC = new jxl.write.WritableCellFormat(wfont);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
// 添加excel标题
/*jxl.write.Label wlabel1 = new jxl.write.Label(5, 0, title, wcfFC);
wsheet.addCell(wlabel1);*/
// 设置列名字体
// 如果有标题的话,要设置一下偏移
int offset = 0;
if (title == null || title.trim().equals("")) {
offset = 0;
} else {
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
wcfFC = new jxl.write.WritableCellFormat(wfont);
}
// 添加excel表头
@SuppressWarnings("rawtypes")
Collection array1 = map.values();
@SuppressWarnings("rawtypes")
Iterator it1 = array1.iterator();
while (it1.hasNext()) {
ExportExcelColumn col = (ExportExcelColumn) it1.next();
wlabel = new jxl.write.Label(col.getIndex(), offset, col.getTitle(), wcfFC);
wsheet.addCell(wlabel);
}
// 设置正文字体
wfont = new jxl.write.WritableFont(WritableFont.TIMES, 14, WritableFont.BOLD, false,
jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
wcfFC = new jxl.write.WritableCellFormat(wfont);
// 往Excel输出数据
int rowIndex = 1 + offset;
@SuppressWarnings("rawtypes")
Collection array = map.values();
for (Object obj : list) {// 循环待导出的list数据集
@SuppressWarnings("rawtypes")
Iterator it = array.iterator();
while (it.hasNext()) {
ExportExcelColumn col = (ExportExcelColumn) it.next();
String value = "";
try {
if (col.getMethodName().equals(serialNumber)) { // 如果是序号,用自增数字赋值
value = String.valueOf(rowIndex);
} else {
value = String.valueOf(invokeNoArgMethod(obj, col.getMethodName()));// 利用反射机制,动态执行pojo类中get方法,获取属性值
}
if ("null".equals(value)) {
value = "";
}
} catch (Exception e) {
e.printStackTrace();
}
wlabel = new jxl.write.Label(col.getIndex(), rowIndex, value);
wsheet.addCell(wlabel);
}
rowIndex++;
}
wbook.write(); // 写入文件
wbook.close();
os.flush();
os.close();
}
/**
* (通用方法,调用即可) 使用反射机制,动态执行方法(无参方法)
*
* @author chen_zhenyu
*/
@SuppressWarnings("unchecked")
public Object invokeNoArgMethod(Object owner, String methodName) throws Exception {
@SuppressWarnings("rawtypes")
Class cls = owner.getClass();
Method method = cls.getMethod(methodName);
return method.invoke(owner);
}
}
(4):在后端controller中设置
/**
* 导出
* @param page
* @param rows
* @param ap
* @return
*/
@ResponseBody
@RequestMapping(value="exportTaxVva")
public Object exportTaxVva(HttpServletRequest request, HttpServletResponse response){
Result result=new Result();
try {
//查询条件
String code=request.getParameter("code");
String nameCN=request.getParameter("brief");
// 封装参数
String name="TaxVva信息详情表";
//当前日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String nowtime=sdf.format(new Date());
name+=nowtime;
name+=".xls";
//excel中标题头
String fieldTitle = "";
//其中serial taxId,shippingType,currencyCode unit value是数据库表对应生成的javaBean
fieldTitle += "serial" + ",";fieldTitle+="taxId"+",";
fieldTitle+="shppingType"+",";
fieldTitle+="currencyCode"+",";
fieldTitle+="unit"+",";
fieldTitle+="value"+",";
//javabean中对应的字段
String dataField = "";
dataField += "serial" + ",";
dataField+="taxId"+",";
dataField+="shppingType"+",";
dataField+="currencyCode"+",";
dataField+="unit"+",";
dataField+="value"+",";
//查询出数据
TaxVvaExample spe = new TaxVvaExample();
TaxVvaExample.Criteria criteria = spe.createCriteria();
List<TaxVva> list =taxVvaServiceExt.selectByExample(spe);
//调用导出excel借口 公用方法,在第三步的时候已经创建好
ExcelOperation<TaxVva> eo=new ExcelOperation<TaxVva>();
eo.exportDataExcel(request, response, name, fieldTitle, dataField,list);
result.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
}
return result;
}
现在基本将数据库里的数据导出到excel中。