POI操纵EXCEL文档之导入文档
Posted samile6899
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POI操纵EXCEL文档之导入文档相关的知识,希望对你有一定的参考价值。
当前主流的后台管理系统,相信都会有文档导入导出的功能。而这其中用到的技术又是多种多样,有用POI框架,也有用JXLS技术的。技术只是手段,项目中实现功能最重要。今天主要说下如何利用POI技术操作EXCEL文档。
=================================================================
POI 操作EXCEL文档导入导出,大致有两种方式:
1. 用户模式(usermodel):一次性将xls文件读入到内存,创建dom结构处理
2. 事件模式(eventusermodel):以流的形式读取xls文件,读取xls文件占用相对较小的内存
-----------------------------------------------------------------------------------------------------------
第一种方式容易造成内存溢出的异常,第二种的话是逐条读取数据,即使文档中有千万条数据,也依然可以正常读取,不会造成内存溢出。今天使用的就是第二中方式,基于事件模式的excel文档导入。具体的两种模式的区别,大家可以网上百度下,了解了这两种模式之后,对于大数据EXCEL导入的优化会有很好的帮助。(参考:http://blog.csdn.net/lipinganq/article/details/77678443 )
**********************************************************************
POI 导入EXCEL文档:(设计思路)
1,首先,要导入EXCEL 文档,就必须要先有导入的模板文件,在这里,我提供好了制作好的EXCEL 模板文件提供下载;(EXCEL文档模板示例下载 )
2,有了EXCEL 模板文件,就开始编写页面,并编写后台逻辑代码了;
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 14-6-26
Time: 下午3:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/aml/includes/amlincludes.jsp" %>
<html>
<head></head>
<script type="text/javascript">
function ${param.perfix}showUpdateWindow(data){
$("#"+"${param.perfix}objid").stk_val("");
$("#"+"${param.perfix}name").text("");
$("#"+"${param.perfix}certno").text("");
$("#"+"${param.perfix}remark").text("");
$("#"+"${param.perfix}oricustid").stk_val("");
$("#"+"${param.perfix}certtype").text("");
var qdiiType = $("#"+"${param.perfix}qdiiType").stk_val();
stk.call({
className:"com.sinitek.sirm.web.amlqd.AmlQDIIRCAction",
method:'getQDIIDetail',
param:{"id":data.objid, "qdiiType":qdiiType},
callBack:function (result) {
$("#"+"${param.perfix}objid").stk_val(result.objid);
$("#"+"${param.perfix}name").text(result.name);
$("#"+"${param.perfix}certno").text(result.certno);
$("#"+"${param.perfix}remark").text(result.remark);
$("#"+"${param.perfix}oricustid").stk_val(result.oricustid);
$("#"+"${param.perfix}certtype").text(result.certtypename);
$("#"+"${param.perfix}editWindow").stk_show({title:"编辑修改"});
}
});
}
var ${param.perfix}uploader = null;
function ${param.perfix}importRLInit(){
if(${param.perfix}uploader==null){
${param.perfix}uploader = new sirm.io.uploader("#"+"${param.perfix}uploader", null, true, [
{title:"批量上传", extensions:"xls"}
]);
}else {
${param.perfix}uploader.clear();
}
}
function ${param.perfix}showAddQDIIListWindow(){
$("#"+"${param.perfix}importWindow").stk_show({title:"批量导入",width:"800px"});
${param.perfix}importRLInit();
}
//批量导入模板
function ${param.perfix}importAmlRiskList(){
$("#"+"${param.perfix}importForm").stk_submit("analystdata", function (result) {
stk.alert(result, "询问", {"确认":function () {
stk.closeDialog();
$("#"+"${param.perfix}importForm").stk_submit("importAmlRiskList", function (result) {
if (result.successCount == 1) {
stk.alert("上传完毕!", "提示", {"确认":function () {
$("#__alertDiv").dialog("close");
$("#"+"${param.perfix}importWindow").stk_hide();
$("#"+"${param.perfix}table").stk_query();
}});
} else {
stk.alert(result.errorinfo);
}
});
},
"取消":function () {
stk.closeDialog();
}});
});
}
function ${param.perfix}remove(){
if ($("#"+"${param.perfix}checkBoxPlugins").hasSelect()) {
stk.confirm("确认删除?", function () {
var qdiiType = $("#"+"${param.perfix}qdiiType").stk_val();
$("#"+"${param.perfix}checkBoxPlugins").stk_call({type:'delete', qdiiType:qdiiType}, function (result) {
$("#"+"${param.perfix}table").stk_query();
});
});
} else {
stk.alert("请选择需删除的数据");
}
}
function ${param.perfix}save(){
$("#"+"${param.perfix}editForm").stk_submit("editQDIIDetail",function(result){
stk.alert(result.code);
if(result.code != null){
$("#"+"${param.perfix}editWindow").stk_hide();
$("#"+"${param.perfix}table").stk_query();
}
});
}
function ${param.perfix}exportAll(fileType){
var funName = fileType == "csv" ? "exportCsv" : fileType == "xls" ? "exportExcel" : "";
$("#"+"${param.perfix}form").stk_submit(funName, function(result){
if(result != ""){
window.location.href = sirm.jsurl(result);
$("#"+"${param.perfix}table").stk_query();
}
});
}
$(document).ready(function(){
$("#"+"${param.perfix}certtypeS").stk_emptyOptions();
var value = "${param.cttpList}";
value = value.replace("{", "").replace("}", "");
var valArr = value.split(",");
for(var i=0; i<valArr.length; i++){
var s = valArr[i].split("=");
$("#"+"${param.perfix}certtypeS").stk_addOptions(s[0], s[1]);
}
});
</script>
<sirm:body>
<ui:form id="${param.perfix}form" clazz="com.sinitek.sirm.web.amlqd.AmlQDIIRCAction">
<input id="${param.perfix}qdiiType" type="hidden" name="qdiiType" value="${param.type}"/>
<table width="100%" class="search-params-bar">
<tr>
<td class="tit">
<label>客户名称:</label>
<ui:textfield id="${param.perfix}nameS" name="name" width="120px"/>
</td>
<td class="tit">
<label>证件号码:</label>
<ui:textfield id="${param.perfix}certnoS" name="certno" width="120px"/>
</td>
<td class="tit" colspan="2">
<label>创建日期:</label>
<ui:datefield id="${param.perfix}startdate_openS" name="startdate_open"
endDate="${param.perfix}enddate_openS"/>
~
<ui:datefield id="${param.perfix}enddate_openS" name="enddate_open"
startDate="${param.perfix}startdate_openS"/>
</td>
<td class="tit" colspan="2">
<label>导出日期:</label>
<ui:datefield id="${param.perfix}exportdate_startS" name="exportdate_start"
endDate="${param.perfix}exportdate_endS"/>
~
<ui:datefield id="${param.perfix}exportdate_endS" name="exportdate_end"
startDate="${param.perfix}exportdate_startS"/>
</td>
</tr>
<tr>
<td class="tit">
<label>证件类型:</label>
<ui:select id="${param.perfix}certtypeS" name="certtype"
headerKey="" headerValue="---请选择---" defaultValue="" width="120px"/>
</td>
<td class="tit">
<label>有无备注:</label>
<ui:select id="${param.perfix}remarkS" name="remark" list="#{'1':'有','0':'无'}"
headerKey="" headerValue="---请选择---" defaultValue=""/>
</td>
<td class="tit" colspan="2">
<ui:button text="查询">
<event:onclick>
$("#"+"${param.perfix}table").stk_query();
</event:onclick>
</ui:button>
</td>
</tr>
</table>
</ui:form>
<plugin:colRowNum id="${param.perfix}rowNumPlugins"/>
<plugin:colCheckbox id="${param.perfix}checkBoxPlugins" name="${param.perfix}check"/>
<plugin:colLink id="${param.perfix}updateBtn" text="修改" dataVar="data">
${param.perfix}showUpdateWindow(data)
</plugin:colLink>
<ui:table id="${param.perfix}table" queryForm="${param.perfix}form" actionClass="com.sinitek.sirm.web.amlqd.AmlQDIIRCAction" pageSize="50" tableWidth="100%">
<layout:tableToolBar position="top">
<ui:toolbarButton text="批量导入" icon="ui-icon-plusthick">
<event:onclick>
${param.perfix}showAddQDIIListWindow();
</event:onclick>
</ui:toolbarButton>
<ui:toolbarButton text="批量删除" icon="ui-icon-minusthick">
<event:onclick>
${param.perfix}remove();
</event:onclick>
</ui:toolbarButton>
<ui:toolbarButton text="导出CSV" icon="ui-icon-gear">
<event:onclick>
${param.perfix}exportAll("csv");
</event:onclick>
</ui:toolbarButton>
<ui:toolbarButton text="导出EXCEL" icon="ui-icon-gear">
<event:onclick>
${param.perfix}exportAll("xls");
</event:onclick>
</ui:toolbarButton>
</layout:tableToolBar>
<ui:col plugin="${param.perfix}checkBoxPlugins" width="35px" />
<ui:col plugin="${param.perfix}rowNumPlugins" width="30px"/>
<ui:col property="name" width="160px" title="客户名称" align="center"/>
<ui:colCust method="getCttpName" width="120px" title="证件类型"/>
<ui:col property="certno" width="120px" title="证件号码" align="center"/>
<ui:col property="remark" width="120px" title="备注" align="center"/>
<ui:col property="create_date" width="200px" title="创建时间" align="center"/>
<ui:col property="export_date" width="200px" title="导出时间" align="center"/>
<ui:col plugin="${param.perfix}updateBtn" title="操作" width="100px"/>
</ui:table>
<layout:window id="${param.perfix}importWindow" width="400px">
<ui:form id="${param.perfix}importForm" clazz="com.sinitek.sirm.web.amlqd.AmlQDIIRCAction" allowFileUpload="true">
<table class="stk-form-ui-st1" width="400px" >
<tr>
<td class="hd" width="120"><br/><br/><br/><br/></td>
<td class="bd" align="left" width="270px">
<input type="hidden" name="datatype" id="${param.perfix}datatype" value="GBK"/>
<div id="${param.perfix}uploader"></div>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<br/>
<a href="/aml/excel/QDIICustomers.xls">下载模板</a>
<ui:button text="批量导入">
<event:onclick>
${param.perfix}importAmlRiskList()
</event:onclick>
</ui:button>
<ui:button text="关 闭">
<event:onclick>
$("#"+"${param.perfix}importWindow").stk_hide()
</event:onclick>
</ui:button>
</td>
</tr>
</table>
</ui:form>
</layout:window>
<layout:window id="${param.perfix}editWindow" width="500px">
<ui:form id="${param.perfix}editForm" clazz="com.sinitek.sirm.web.amlqd.AmlQDIIRCAction">
<input type="hidden" name="id" id="${param.perfix}objid"/>
<input id="${param.perfix}qdiiType" type="hidden" name="qdiiType" value="${param.type}"/>
<table class="stk-form-ui-st1">
<tr>
<td class="hd" width="140">客户名称</td>
<td class="bd" width="auto">
<ui:label id="${param.perfix}name" name="name"></ui:label>
</td>
</tr>
<tr>
<td class="hd" width="140">证件类型</td>
<td class="bd" width="auto">
<ui:label id="${param.perfix}certtype" name="certtype"></ui:label>
<%-- <%–<ui:select id="certtypeQ" name="certtype" list="#attr.cttpList" listKey="key"
listValue="value" width="120px"
headerKey="" headerValue="请选择" defaultValue=""/>–%>--%>
</td>
</tr>
<tr>
<td class="hd" width="140">证件号码</td>
<td class="bd" width="auto">
<ui:label id="${param.perfix}certno" name="certno"></ui:label>
</td>
</tr>
<tr>
<td class="hd" width="140">客户ID</td>
<td class="bd" width="auto">
<ui:textfield id="${param.perfix}oricustid" name="oricustid"></ui:textfield>
</td>
</tr>
<tr>
<td class="hd" width="140">备注</td>
<td class="bd" width="auto">
<%--<ui:textfield id="remarkQ" name="remark"/>--%>
<ui:textarea rows="8" width="250px" id="${param.perfix}remark" name="remark"/>
</td>
</tr>
</table>
<br/>
<div align="center">
<ui:button text="保 存">
<event:onclick>
if ($("#"+"${param.perfix}editForm").stk_checkForm()) {
${param.perfix}save();
}
</event:onclick>
</ui:button>
<ui:button text="取 消">
<event:onclick>
$("#"+"${param.perfix}editWindow").stk_hide()
</event:onclick>
</ui:button>
</div>
<func:checkers formId="${param.perfix}editForm">
<%--<func:checker target="nameQ" allowBlank="false" blankText="客户名称不能为空"/>
<func:checker target="certtypeQ" allowBlank="false" blankText="证件类型不能为空!" />
<func:checker target="certnoQ" allowBlank="false" blankText="证件号码不能为空!" />--%>
<func:checker target="remark" allowBlank="false" blankText="备注不能为空!" />
</func:checkers>
</ui:form>
</layout:window>
</sirm:body>
</html>
后台的ACTION :
package com.sinitek.sirm.web.amlqd;
import com.sinitek.sirm.busin.aml.service.AmlServiceFactory;
import com.sinitek.sirm.busin.aml.service.impl.AmlQDIIListServiceImpl;
import com.sinitek.sirm.busin.aml.utils.*;
import com.sinitek.sirm.common.utils.StringUtil;
import com.sinitek.sirm.common.web.RequestContext;
import com.sinitek.sirm.common.web.tag.PageLoadContext;
import com.sinitek.sirm.framework.utils.io.Uploader;
import com.sinitek.sirm.framework.utils.io.UploaderFile;
import com.sinitek.sirm.framework.utils.io.UploaderFileList;
import com.sinitek.spirit.webcontrol.table.ICheckBoxPluginAware;
import com.sinitek.spirit.webcontrol.table.ITableAware;
import org.directwebremoting.io.FileTransfer;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by user on 2016/4/21.
*/
public class AmlQDIIRCAction implements ITableAware,ICheckBoxPluginAware {
public static final String TYPE_RC = "rc";
public static final String TYPE_DQ = "dq";
public static void loadpage(PageLoadContext context) {
context.getPageContext().setAttribute("cttpList", AmlServiceFactory.getAmlOptionsService().getOptionMap(OptionsUtils.citpList));
}
@Override
public Object callCheckBoxPlugin(List<Map> list, Map map, HttpServletRequest httpServletRequest) throws Exception {
String type = StringUtil.safeToString(map.get("type"), "");
String qdiiType = StringUtil.safeToString(map.get("qdiiType"), "");
String result = "";
if (type.equals("delete")) {
if (list != null && list.size() > 0) {
if (qdiiType.equals(TYPE_RC)) {
for (Map p : list) {
String id = (String) p.get("id");
result += AmlServiceFactory.getAmlQDIIListService().delQDIIRC(id);
}
} else if(qdiiType.equals(TYPE_DQ)){
for (Map p : list) {
String id = (String) p.get("id");
result += AmlServiceFactory.getAmlQDIIListService().delQDIIDQ(id);
}
}
}
}
return result;
}
@Override
public Object getResult(Map<String, String> map, HttpServletRequest httpServletRequest) throws Exception {
String qdiiType = StringUtil.safeToString(map.get("qdiiType"), "");
if (qdiiType.equals(TYPE_RC)) {
return AmlServiceFactory.getAmlQDIIListService().getAmlQDIIRC(map);
} else if(qdiiType.equals(TYPE_DQ)){
return AmlServiceFactory.getAmlQDIIListService().getAmlQDIIDQ(map);
} else{
return null;
}
}
@Override
public String setDefaultOrderBy(Map<String, String> map, HttpServletRequest httpServletRequest) throws Exception {
return "id desc";
}
public String analystdata(Map<String, String> map, Map<String, List<FileTransfer>> fileMap, HttpServletRequest request) {
//获取临时目录。
UploaderFileList fileList = Uploader.parseRequest(map);
StringBuffer name = new StringBuffer("上传文档名称为:");
int i = 0;
for(UploaderFile file:fileList)
{
name.append("<br/>[" + (++i) + "] " + file.getUploadName());
}
return name.toString();
}
public Object importAmlRiskList(Map<String, String> map, Map<String, List<FileTransfer>> fileMap, HttpServletRequest request) {
Map result=new HashMap();
//获取临时目录。
UploaderFileList files = Uploader.parseRequest(map);
if(files.size() > 1)
{
result.put("errorinfo","一次只能上传一个xls文档");
}
if (files.size()==1) {
for(UploaderFile file:files){
try {
result = importFile(file);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
result.put("errorinfo",e.getMessage());
break;
}
}
}
return result;
}
/**
* 批量导入EXCEL文档
* @param uploadFile
* @return
* @throws Exception
*/
private Map importFile(UploaderFile uploadFile) throws Exception {
Map result=new HashMap();
String uploadFilePath = uploadFile.getPath();
//评分表名称格式 PFB-YYYYMMDD.XLS
if(!FileUtils.getAffix(uploadFilePath)[1].toLowerCase().equals(".xls")){
throw new Exception("请选择正确类型的文件!");
}
Map currUser=new HashMap();
currUser.put("orgid",RequestContext.getCurrentUser().getOrgId());
int successCount = importAmlRiskListByExecls(uploadFilePath);
result.put("successCount",successCount);
return result;
}
public static void uploadFile(InputStream fis,String attachmentName){
FileOutputStream fos = null;
try{
fos = new FileOutputStream(new File(attachmentName));
byte[] buffer = new byte[1024*1024];
while(true){
int length = fis.read(buffer);
if(length < 0) break;
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
}catch(IOException ioe) {
ioe.printStackTrace();
}finally{
if(fis != null){
try{
fis.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
if(fos != null){
try{
fos.close();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static String getCttpName(Map map){
String type=StringUtil.safeToString(map.get("certtype"), "");
Map mpes= AmlServiceFactory.getAmlOptionsService().getOptionMap(OptionsUtils.citpList);
for(Object keys : mpes.keySet()){
if(keys.equals(type)){
type=mpes.get(keys).toString(); //证件类型
}
}
return type;
}
public int importAmlRiskListByExecls(String fileName) {
int successCount =1;
ExcelUtil excelUtil = new ExcelUtil();
List excelList = excelUtil.readDataFromExcelThrowsException(fileName);
insertAmlQDIIRCImports(excelList);
return successCount;
}
public void insertAmlQDIIRCImports(List list) {
list.remove(0);// 去掉表头
int len = list.size();
if (len == 0) {
return;
}
String rc_groupid = AmlServiceFactory.getAmlQDIIListService().getNextValue_Seq("SEQ_CUSTOMER_QDII_RC_GROUPID");
for (int i = 0; i < len; i++) {
StringBuffer sqlBuf = new StringBuffer("");
List rowList = (List) list.get(i);
if (rowList.size() < 3){
break;// 格式不正确
}
String name = StringUtil.safeToString(rowList.get(0), "");
String certno = StringUtil.safeToString(rowList.get(2), "");
String remark = StringUtil.safeToString(rowList.get(3), "");
DateFormat date=new SimpleDateFormat("yyyy-MM-dd");
String create_date = date.format(new Date());
String certtype = "";
String certtypeName = StringUtil.safeToString(rowList.get(1), "");
Map mpes = AmlServiceFactory.getAmlOptionsService().getOptionMap(OptionsUtils.citpList);
for(Object keys : mpes.keySet()){
if(mpes.get(keys).equals(certtypeName)){
certtype = keys.toString(); //证件类型
break;
}
}
boolean flag = false;
String oricustid=""; //原始客户ID
Map param=new HashMap();
param.put("certtype", certtype);
param.put("certno", certno);
List listes = AmlServiceFactory.getAmlQDIIListService().findQDIICustInfo(param);
/**
* 证件类型+证件号码->全量客户中查找对应原始客户ID
* 1.找到:用原始客户ID匹配QDII日常客户的原始客户ID,存在,不插;不存在,插;
* 2.没找到:用证件类型+证件号码 匹配QDII日常客户的 证件类型+证件号码,存在,不插;不存在,插;
*/
if(listes!=null && listes.size()>0) {
Map map = (Map) listes.get(0);
oricustid = map.get("oricustid").toString();
param.clear();
param.put("oricustid", oricustid);
int count = AmlServiceFactory.getAmlQDIIListService().countDQIIRCCust(param);
if (count == 0) {
flag = true;
}
} else {
param.clear();
param.put("certtype", certtype);
param.put("certno", certno);
int count = AmlServiceFactory.getAmlQDIIListService().countDQIIRCCust(param);
if (count == 0) {
flag = true;
}
}
if(flag){
Map dqii_rc = new HashMap();
dqii_rc.put("batgroupid", rc_groupid);
dqii_rc.put("oricustid", oricustid);
dqii_rc.put("name", name);
dqii_rc.put("certtype", certtype);
dqii_rc.put("certno", certno);
dqii_rc.put("create_date", create_date);
dqii_rc.put("create_oper", RequestContext.getCurrentUser().getOrgId());
dqii_rc.put("remark", remark);
dqii_rc.put("flag", "1");
try {
Map temp = AmlServiceFactory.getAmlServiceHelper().save(dqii_rc, "AML_DM_CUSTOMER_QDII_RC", "id", "SEQ_CUSTOMER_QDII_RC_ID");
} catch (Exception e){
}
}
}
}
}
EXCELUtil 工具类:
/*
* Created on 2005-3-14
*/
package com.sinitek.sirm.busin.aml.utils;
/**
* @author ray.huang
*/
import com.sinitek.sirm.common.utils.IOUtil;
import com.sinitek.sirm.common.web.RequestContext;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;
public class ExcelUtil {
public static final int pageNum = 10000000;//每个worksheet显示的数据条数
public static String writeExcel(String excelPath,String reportName,List colName,List data,List datap,String tableName){
//打开文件
String fileName = "";
String excelName = "";
try{
//String excelPath = ExcelConfig.getInstance().excelFile;
//String excelPath = Config.getConfig("excel");
//FinderManager fm = new FinderManager();
excelName =reportName+".xls";
fileName = excelPath+System.getProperty("file.separator")+excelName;
createFile(fileName);
WritableWorkbook book = Workbook.createWorkbook(new File(fileName));
//计算列数
int j = 1;
int k = 2;
int sheetNum = 0;
WritableSheet sheet = book.createSheet("第1页",sheetNum);
int colNameLen = colName.size();
int middle = (colNameLen/2)-1;
//打印标题
Label label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
WritableFont wf = new WritableFont(WritableFont.ARIAL,10, WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 设置写入字体
WritableCellFormat wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setBackground(Colour.GRAY_25);
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString(),wcfF);
sheet.addCell(label);
}
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
if(j%pageNum == 0){
int count = sheetNum+2;
sheet = book.createSheet("第"+count+"页",sheetNum);
//打印标题
label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString()==null?"":colName.get(i).toString());
sheet.addCell(label);
}
sheetNum++;
k = 2;
}
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
int dataLen2 = datap.size();
for(int n=0;n<dataLen2;n++){
if(j%pageNum == 0){
int count = sheetNum+2;
sheet = book.createSheet("第"+count+"页",sheetNum);
//打印标题
label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString()==null?"":colName.get(i).toString());
sheet.addCell(label);
}
sheetNum++;
k = 2;
}
List data3 = (List)datap.get(n);
int dataSize = data3.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data3.get(i) != null && !data3.get(i).equals("")){
dataValue = data3.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
/**
* @param colName 头的名称
* @param Data 显示的数据
*/
public static String writeExcel(String excelPath,String reportName,List colName,List data,String tableName){
//打开文件
String fileName = "";
String excelName = "";
try{
//String excelPath = ExcelConfig.getInstance().excelFile;
//String excelPath = Config.getConfig("excel");
//FinderManager fm = new FinderManager();
excelName =reportName+".xls";
fileName = excelPath+System.getProperty("file.separator")+excelName;
createFile(fileName);
WorkbookSettings workbookSettings=new WorkbookSettings();
workbookSettings.setEncoding("ISO-8859-1"); //关键代码,解决中文乱码
WritableWorkbook book = Workbook.createWorkbook(new File(fileName), workbookSettings);
//计算列数
int j = 1;
int k = 2;
int sheetNum = 0;
WritableSheet sheet = book.createSheet("第1页",sheetNum);
int colNameLen = colName.size();
int middle = (colNameLen/2)-1;
//打印标题
Label label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
WritableFont wf = new WritableFont(WritableFont.ARIAL,10, WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 设置写入字体
WritableCellFormat wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setBackground(Colour.GRAY_25);
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString(),wcfF);
sheet.addCell(label);
}
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
if(j%pageNum == 0){
int count = sheetNum+2;
sheet = book.createSheet("第"+count+"页",sheetNum);
//打印标题
label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString()==null?"":colName.get(i).toString());
sheet.addCell(label);
}
sheetNum++;
k = 2;
}
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
/**
* 将法人信息合并到同一页中
* @author weifeng.tao
* @date 2009.08.26
* */
public static String updateExcel(String excelPath,List colName,List data){
//打开文件
String excelName = excelPath;
try{
Workbook wb = Workbook.getWorkbook(new File(excelPath));
WritableWorkbook book = Workbook.createWorkbook(new File(excelPath), wb);
//计算列数
WritableSheet sheet = book.getSheet(0);
int k = sheet.getRows();
//打印头
WritableFont wf = new WritableFont(WritableFont.ARIAL,10, WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 设置写入字体
WritableCellFormat wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setBackground(Colour.BLACK);
Label label = new Label(0,0,"");
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
public static String updateExcel(String excelPath,List colName,List data,String tableName,int page){
//打开文件
String excelName = excelPath;
try{
//String excelPath = ExcelConfig.getInstance().excelFile;
//String excelPath = Config.getConfig("excel");
Workbook wb = Workbook.getWorkbook(new File(excelPath));
WritableWorkbook book = Workbook.createWorkbook(new File(excelPath), wb);
//WritableWorkbook book = Workbook.createWorkbook(new File(excelPath),wb);
//计算列数
int j = 1;
int k = 2;
WritableSheet sheet = book.createSheet("第2页",page);
int colNameLen = colName.size();
int middle = (colNameLen/2)-1;
//打印标题
Label label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
WritableFont wf = new WritableFont(WritableFont.ARIAL,10, WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);// 设置写入字体
//NumberFormat nf = new jxl.write.NumberFormat("#"); //设定带小数点数字格式
//WritableCellFormat wcfF = new WritableCellFormat(wf, nf);// 设置CellFormat
WritableCellFormat wcfF = new WritableCellFormat(wf);// 设置CellFormat
wcfF.setBackground(Colour.BLACK);
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString(),wcfF);
sheet.addCell(label);
}
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
if(j%pageNum == 0){
int count = page+2;
sheet = book.createSheet("第"+count+"页",page);
//打印标题
label=new Label(middle,0,tableName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString()==null?"":colName.get(i).toString());
sheet.addCell(label);
}
page++;
k = 2;
}
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
public static String writeExcelpageSize(String excelPath,String reportName,List colName,List data,WritableWorkbook book,int gg){
//打开文件
String excelName = "";
try{
//计算列数
int j = 1;
int k = 2;
int sheetNum = gg;
WritableSheet sheet = book.createSheet("第"+gg+"页",gg);
int colNameLen = colName.size();
int middle = colNameLen/2;
//打印标题
Label label=new Label(middle,0,reportName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString());
sheet.addCell(label);
}
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
if(j%pageNum == 0){
int count = sheetNum+2;
sheet = book.createSheet("第"+count+"页",sheetNum);
//打印标题
label=new Label(middle,0,reportName);
sheet.addCell(label);
//打印头
for(int i=0;i<colNameLen;i++){
label=new Label(i,1,colName.get(i).toString()==null?"":colName.get(i).toString());
sheet.addCell(label);
}
sheetNum++;
k = 2;
}
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
/**
*
* @param Data 显示的数据
*/
public static String writeExcelPage(String excelPath,String reportName,List data){
//打开文件
String fileName = "";
String excelName = "";
try{
excelName =reportName+".xls";
fileName = excelPath+System.getProperty("file.separator")+excelName;
createFile(fileName);
WritableWorkbook book = Workbook.createWorkbook(new File(fileName));
//计算列数
int j = 1;
int k = 2;
int sheetNum = 0;
WritableSheet sheet = book.createSheet("第1页",sheetNum);
int dataLen = data.size();
for(int n=0;n<dataLen;n++){
List data2 = (List)data.get(n);
int dataSize = data2.size();
for(int i=0;i<dataSize;i++){
String dataValue = "";
if(data2.get(i) != null && !data2.get(i).equals("")){
dataValue = data2.get(i).toString();
}
Label label=new Label(i,k,dataValue);
sheet.addCell(label);
}
k++;
j++;
}
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e){
e.printStackTrace();
}
return excelName;
}
/**
* 得到excel文件头名称的list
* @param fileName excel文件
* @return
*/
public List getHeadList(String fileName){
List headList = new ArrayList();
try{
Workbook book = Workbook.getWorkbook(new File(fileName));
//获得第一个工作表对象
Sheet sheet=book.getSheet(0);
//得到excel文件的列的长度
int colLen = sheet.getColumns();
for(int i=0;i<colLen;i++){
Cell cell = sheet.getCell(0,i);
headList.add(cell.getContents());
}
book.close();
}catch(Exception e){
e.printStackTrace();
}
return headList;
}
/**
* 产生excel文件
* @param fileName
* @return
* @throws java.io.IOException
* @throws Exception
*/
public static boolean createFile(String fileName)throws IOException ,Exception{
File file = new File(fileName);
if (file.exists()){
if (file.canWrite() == false)
return false;
}else{
String path = null; /* Does not exist. Create the directories */
int firstSlash = fileName.indexOf(File.separatorChar);
int finalSlash = fileName.lastIndexOf(File.separatorChar);
if(finalSlash == 0){
/* error, not valid path */
}else if (finalSlash == 1){ /* UNIX root dir */
path = File.separator;
}else if (firstSlash == finalSlash){ /* for example c:\\ Then make sure slash is part of path */
path = fileName.substring(0,finalSlash+1);
}else{ path = fileName.substring(0,finalSlash); }
File dir = new File(path);
dir.mkdirs();
}
return true;
}
/**
* 从excel文件里读取数据,此方法只针对行列规则的excel文件
* 返回结果是一行为一个list,整个文件本身为一个大的list
* @param fileName excel文件名
* @return
*/
public static List readDataFromExcel(String fileName) throws Exception {
List allDataList = new ArrayList();
try{
InputStream is = new FileInputStream(fileName);//读取文件
Workbook rwb = Workbook.getWorkbook(is);
int sheetCount = rwb.getNumberOfSheets();
System.out.println("表单总数==="+sheetCount);
String[] sheetName= rwb.getSheetNames();
for(int k=0;k<sheetCount;k++){
System.out.println("表单名称==="+sheetName[k].toString());
Sheet rs = rwb.getSheet(sheetName[k].toString());//得到第一个工作表单
int col = rs.getColumns(); //得到excel文件的列数
int rol = rs.getRows();//excel文件的行数
System.out.println("得到excel文件的列数"+col);
System.out.println("excel文件的行数"+rol);
for(int j=0;j<rol;j++){
List rowList = new ArrayList();
for(int i=0;i<col;i++){
Cell cell = rs.getCell(i,j);
String data = cell.getContents();
rowList.add(data);
}
allDataList.add(rowList);
}
}
is.close();
rwb.close();
}catch(Exception e){
throw new Exception("导入文件格式错误");//导入文件格式错误
}
return allDataList;
}
/**
* 从excel文件里读取数据,此方法只针对行列规则的excel文件
* 只读一个sheet的情况下
* 返回结果是一行为一个list,整个文件本身为一个大的list
* @param fileName excel文件名
* @return
*/
public List readDataFromExcelThrowsException(String fileName) {
List allDataList = new ArrayList();
try{
InputStream is = new FileInputStream(fileName);//读取文件
Workbook rwb = Workbook.getWorkbook(is);
Sheet rs = rwb.getSheet(0);//得到第一个工作表单
System.out.println(rs.getName());
int col = rs.getColumns(); //得到excel文件的列数
int rol = rs.getRows();//excel文件的行数
for(int j=0;j<rol;j++){
List rowList = new ArrayList();
for(int i=0;i<col;i++){
Cell cell = rs.getCell(i,j);
String data = cell.getContents();
rowList.add(data);
}
allDataList.add(rowList);
}
}catch(Exception e){
e.printStackTrace();
}
//删除空值
for(int i=0;i<allDataList.size();i++){
List tempList = (List) allDataList.get(i);
int flag = 0;
for(Object tempSting : tempList){
if(!((String)tempSting).equals("")){
flag = 1;
break;
}
}
if(flag == 0){
allDataList.remove(i);}
}
return allDataList;
}
/**
* 从excel文件里读取数据,此方法只针对行列规则的excel文件
* 只读一个sheet的情况下
* 返回结果是一行为一个list,整个文件本身为一个大的list
* @param fileName excel文件名
* @param sheet 选中的工作单元
* @return
*/
public List readDataFromExcelBySheet(String fileName,int sheet) throws Exception{
List allDataList = new ArrayList();
InputStream is = new FileInputStream(fileName);//读取文件
Workbook rwb = Workbook.getWorkbook(is);
Sheet rs = rwb.getSheet(sheet);//得到第一个工作表单
int col = rs.getColumns(); //得到excel文件的列数
int rol = rs.getRows();//excel文件的行数
for(int j=0;j<rol;j++){
List rowList = new ArrayList();
for(int i=0;i<col;i++){
Cell cell = rs.getCell(i,j);
String data = cell.getContents();
rowList.add(data);
}
allDataList.add(rowList);
}
return allDataList;
}
/**
* 得到excel的sheet map
* @param fileName
* @return
* @throws Exception
*/
public HashMap getSheetNameMap(String fileName) throws Exception{
InputStream is = new FileInputStream(fileName);//读取文件
Workbook rwb = Workbook.getWorkbook(is);
HashMap map = new HashMap();
int sheetSize = rwb.getNumberOfSheets();
for(int i=0;i<sheetSize;i++){
map.put(new Integer(i),rwb.getSheet(i).getName());
}
return map;
}
public static void main(String args[]){
ExcelUtil util = new ExcelUtil();
}
public static String export_JXLS(Map dataMap, String fileName, String templatePath) {
HttpServletRequest request = RequestContext.getRequest();
XLSTransformer transformer = new XLSTransformer();
String xlsTemplateFileName = request.getSession().getServletContext().getRealPath(templatePath);
Map beans = new HashMap();
beans.put("list1", dataMap.get("list1"));
String path = "";
try {
File file = IOUtil.copyToTempDir(new File(xlsTemplateFileName));
InputStream i = new FileInputStream(file);
org.apache.poi.ss.usermodel.Workbook workbook = transformer.transformXLS(i, beans);
String _savepath = IOUtil.getTempDir().getPath() + File.separatorChar + fileName;
File _tempfile = IOUtil.createTempFile();
OutputStream os = new FileOutputStream(_tempfile);
workbook.write(os);
IOUtil.copy(new FileInputStream(_tempfile), new FileOutputStream(_savepath));
path = _savepath;
os.close();
} catch (IOException e) {
//LOGGER.error("Stream读写出错", e);
} catch (InvalidFormatException e) {
//LOGGER.error("模板转换出错", e);
}
return path;
}
}
具体的保存到数据库中的方法就不详细写了,大体上的方法就是这样,大家可以试一试。当然了,由于各个机构公司使用的框架不同,后台业务逻辑不同,导致方法可能会有所小的改动,但是本质的方法都是一样的。例子中的框架是自己机构独有的,因此大家在测试的时候,不可照搬照照挪,要注意稍微改动下,本例只是一个启发的作用,希望能有更好的方法,欢迎留言讨论哦!
==================================================
后续:
对于EXCEL导出,可能对于很多新手刚入行的程序员还是一个有点难度的问题。
所以在这里的话,我也做了一个小的DEMO给大家,希望对于新人能够有所帮助和学习。这个小的DEMO在导入速度和性能上也都还好,EXCEL单个sheet中最多支持的20000条数据,我做了下测试,只需要1分12秒的时候解析完成,还是很快的。当然了,对于大神来说,这可能不算什么,也许代码还能继续优化,希望看过DEMO的网友能够继续优化,也欢迎大家更多和我分享和交流。(DEMO下载地址: http://download.csdn.net/download/samile6899/10171204 )
以上是关于POI操纵EXCEL文档之导入文档的主要内容,如果未能解决你的问题,请参考以下文章