Web中導入Excel文件
ExtJs前端代碼:
//=========上傳Excel=============================
uploadPanel = new Ext.form.FormPanel({
fileUpload: true,
id:'fileUploadForm',
frame:true,
labelAlign:'right',
buttonAlign:'center',
labelWidth: 60,
items: [{
xtype: 'textfield',
fieldLabel: '文件',
id: 'file',
inputType: 'file'
}],
buttons: [{
text:'提交',
id:'tijiao',
handler:function(){
var src=Ext.getCmp('file').getValue();
var filetype=src.split('.');
if(filetype[filetype.length-1].toLowerCase()!='xls'){
Ext.Msg.alert('提示','請選擇Excel文件!',function(){
uploadPanel.getForm().getEl().dom.reset();
Ext.getCmp('file').focus();
});
return;
}
if(src==''){
Ext.getCmp('file').focus();
return;
}
uploadPanel.getForm().submit({
method : 'post',
url:'paAction.do?actionType=uploadExcel',
waitTitle: '請稍後',
waitMsg: '正在導入 ...',
success : function(form, action){
if(action.result.success=='true'){
Ext.Msg.alert('提示','導入成功!',function(){
uploadPanel.getForm().getEl().dom.reset();
win4.hide();
store1.removeAll();
store1.reload();
win.show();
});
}else{
Ext.Msg.alert('提示','導入失敗!');
}
},
failure: function(form, action){
Ext.Msg.alert('提示','導入失敗!');
}
});
}
},{
text: '關閉',
handler:function(){
win4.hide();
}
}]
});
var win4= new Ext.Window({
title:'輸入/導入數據',
width: 350,
height:150,
layout: 'fit',
shadow:false,
plain:true,
bodyStyle:'padding:5px;',
closeAction:'hide',
items:uploadPanel
});
win4.on('hide',function(){
uploadPanel.getForm().getEl().dom.reset();
});
java後臺代碼:
public ActionForward uploadExcel(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws
IOException, ServletException, SQLException, Exception {
String user_id = httpServletRequest.getSession().getAttribute("user_id").
toString();
String ip = httpServletRequest.getRemoteHost();
ArrayList plans = new ArrayList();
String newFullNewPath = "";
String returnvalue = "";
boolean success = true;
uploadForm fileForm = (uploadForm) actionForm;
//System.out.println(fileForm);
FormFile file = fileForm.getFile();
String filePath = httpServletRequest.getSession().getServletContext().
getRealPath("/");
try {
newFullNewPath = filePath + "\\Excel\\";
File f = new File(newFullNewPath);
if (!f.isDirectory()) {
f.mkdirs();
}
newFullNewPath = newFullNewPath + file.getFileName().toString();
InputStream is = file.getInputStream();
FileOutputStream foutput = new FileOutputStream(new File(newFullNewPath), false);
BufferedOutputStream bos = new BufferedOutputStream(foutput);
int len = 0;
byte[] buffer = new byte[8192];
while ( (len = is.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, len);
}
is.close();
bos.close();
foutput.close();
}
catch (FileNotFoundException e) {
success = false;
e.printStackTrace();
}
catch (IOException e) {
success = false;
e.printStackTrace();
}
plans = readExcel(newFullNewPath);
success = insert(plans, user_id,ip);
file.destroy();
File ff = new File(newFullNewPath);
ff.delete();
returnvalue = "{success:'" + success + "',oper_id:'" + user_id + "'}";
try {
httpServletResponse.setContentType("text/html; charset=utf-8");
httpServletResponse.getWriter().write(returnvalue);
}
catch (IOException ex) {
ex.printStackTrace();
}
return actionMapping.findForward("");
}
//讀取Excel文檔(excel2003)
protected ArrayList readExcel(String filePath) {
ArrayList pm_dn_plan_s = new ArrayList();
ArrayList pm_dn_plandata = null;
Workbook rwb = null;
Sheet rs = null;
try {
InputStream is = new FileInputStream(filePath);
rwb = Workbook.getWorkbook(is);
//封裝明細數據
rs = rwb.getSheet(0);
for (int i = 1; i < rs.getRows(); i++) {
pm_dn_plandata = new ArrayList();
pm_dn_plandata.add(rs.getCell(0, i).getContents().trim());
pm_dn_plandata.add(rs.getCell(1, i).getContents().trim());
if(rs.getCell(2, i).getType()==CellType.NUMBER|| rs.getCell(2, i).getType()==CellType.NUMBER_FORMULA){
DecimalFormat df = new DecimalFormat("###.0000");
NumberCell nc=(NumberCell)rs.getCell(2, i);
pm_dn_plandata.add(df.format(nc.getValue()));
}else {
pm_dn_plandata.add(rs.getCell(2, i).getContents().trim());
}
pm_dn_plandata.add(rs.getCell(3, i).getContents().trim());
pm_dn_plandata.add(rs.getCell(4, i).getContents().trim());
pm_dn_plandata.add(rs.getCell(5, i).getContents().trim());
pm_dn_plan_s.add(pm_dn_plandata);
}
is.close();
rwb.close();
}
catch (Exception e) {
e.printStackTrace();
}
return pm_dn_plan_s;
}
//插入臨時表
public boolean insert(ArrayList Dn_tongzhi_s, String user_id,String ip) throws
IOException, ServletException, SQLException, Exception {
boolean returnvalue = true;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
DataSource datasource = null;
ServletContext context = null;
context = servlet.getServletContext();
datasource = (DataSource) context.getAttribute(Globals.DATA_SOURCE_KEY);
conn = datasource.getConnection();
conn.setAutoCommit(false);
ArrayList evdata=null;
//定義變量,用來判斷當為空字符串的時候,整形的賦值為0
String evdata2="";
//插入表頭
stmt = conn.createStatement();
String sqlString ="";
try {
//插入明細表
stmt.addBatch("delete pa_data_temp where oper_id='"+user_id+"' and ip='"+ip+"'");
for (int i = 0; i < Dn_tongzhi_s.size(); i++) {
evdata = new ArrayList();
evdata = (ArrayList) Dn_tongzhi_s.get(i);
if (evdata.get(2).equals(""))
{
evdata2="0";
}else{
evdata2=evdata.get(2).toString();
}
sqlString ="insert into pa_data_temp(mat_id,mat_name,qty,deliver_by,used,notes,oper_id,ip) values('"+
evdata.get(0)+"','"+ evdata.get(1)+"','"+ evdata2+"','"+ evdata.get(3)+
"','"+ evdata.get(4)+"','"+ evdata.get(5)+"','"+ user_id+"','"+ ip+"')";
// System.out.println(sqlString);
stmt.addBatch(sqlString);
}
stmt.executeBatch();
conn.setAutoCommit(true);
}
catch (SQLException e) {
returnvalue = false;
conn.rollback();
System.err.println(e.getMessage());
conn.setAutoCommit(true);
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException e) {
rs = null;
}
}
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
stmt = null;
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
conn = null;
}
}
}
return returnvalue;
}
//插入正式表
public ActionForward insert_zhengshi(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws
IOException, ServletException, SQLException {
HashMap maplist = new HashMap();
String returnvalue = "";
boolean success = true;
String sqlString ="";
String ip = httpServletRequest.getRemoteHost();
String user_id = httpServletRequest.getSession().getAttribute("user_id").
toString();
String json1 = java.net.URLDecoder.decode(httpServletRequest.getParameter("json"), "utf-8").replace('"', ' ').trim();
json1 = java.net.URLDecoder.decode(json1, "utf-8").replace('"', ' ').trim();
//System.out.println(json1);
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
DataSource datasource = null;
ServletContext context = null;
context = servlet.getServletContext();
datasource = (DataSource) context.getAttribute(Globals.DATA_SOURCE_KEY);
conn = datasource.getConnection();
stmt = conn.createStatement();
conn.setAutoCommit(false);
try {
ArrayList list = json.jsonstrToarraylist(json1);
String mat_name="";
String used="";
String notes="";
for (int i = 0; i < list.size(); i++) {
maplist = (HashMap) list.get(i);
mat_name=json.toTeshuStr(maplist.get("pmat_name").toString().replaceAll("'", "").trim());
used=json.toTeshuStr(maplist.get("used").toString().replaceAll("'", "").trim());
notes=json.toTeshuStr(maplist.get("notes").toString().replaceAll("'", "").trim());
sqlString = "update pa_data_temp set mat_id=" +maplist.get("pmat_id")+",mat_name='"+mat_name+"',deliver_by="+maplist.get("deliver_by")+",qty="+maplist.get("qty")+" ,pa_no="+maplist.get("pa_no")+
",used='"+used+"',notes='"+notes+"' where pa_detail_id="+ maplist.get("detail_id");
// System.out.println(sqlString);
stmt.executeUpdate(sqlString);
}
sqlString="insert into pa_data(pa_no,mat_id,mat_name,qty,deliver_by,used,notes)"+
" select ltrim(pa_no) as pa_no, ltrim(mat_id) as mat_id, ltrim(mat_name) as mat_name,qty,deliver_by, ltrim(used) as used, ltrim(notes) as notes "+
"from pa_data_temp where oper_id='"+user_id+"'and ip='"+ip+"'";
System.out.println(sqlString);
stmt.addBatch(sqlString);
stmt.executeBatch();
returnvalue = "保存成功!";
conn.setAutoCommit(true);
}
catch (SQLException e) {
conn.rollback();
conn.setAutoCommit(true);
System.err.println(e.getMessage());
success = false;
returnvalue = "保存失敗!";
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException e) {
rs = null;
}
}
if (stmt != null) {
try {
stmt.close();
}
catch (SQLException e) {
stmt = null;
}
}
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
conn = null;
}
}
}
returnvalue = "{success:'" + success + "',msg:'" + returnvalue + "'}";
try {
httpServletResponse.setContentType("text/json; charset=utf-8");
httpServletResponse.getWriter().write(returnvalue);
}
catch (IOException ex) {
ex.printStackTrace();
}
return actionMapping.findForward("");
}
//讀取exec文檔(execl2007,2003)
protected ArrayList readExcel(String excelPath) throws InvalidFormatException, FileNotFoundException, IOException
{
Workbook workbook = WorkbookFactory.create(new FileInputStream(new File(excelPath)));
Sheet sheet = workbook.getSheetAt(0);
int startRowNum = sheet.getFirstRowNum();
int endRowNum = sheet.getLastRowNum();
ArrayList pm_dn_plan_s = new ArrayList();
ArrayList pm_dn_plandata = null;
boolean check = true;
//第一行標題不要
for(int rowNum = startRowNum+1;rowNum<=endRowNum;rowNum++){
Row row = sheet.getRow(rowNum);
if (row == null)continue;
int startCellNum = row.getFirstCellNum();
int endCellNum = row.getLastCellNum();
if(endCellNum<2){
check = false;
break;
}else{
//只讀第一第二列
pm_dn_plandata = new ArrayList();
for (int cellNum = startCellNum; cellNum < endCellNum; cellNum++) {
//pm_dn_plandata = new ArrayList();
Cell cell = row.getCell(cellNum);
if(cellNum==0){
if(cell.getCellType()!=Cell.CELL_TYPE_STRING){
check = false;
break;
}
pm_dn_plandata.add(cell.getStringCellValue());
}
if(cellNum==1){
if(cell.getCellType()!=Cell.CELL_TYPE_NUMERIC){
check = false;
break;
}
pm_dn_plandata.add(cell.getNumericCellValue());
}
}
pm_dn_plan_s.add(pm_dn_plandata);
}
//只讀第一第二列
//if(endCellNum)
//System.out.println();
}
if(!check){
pm_dn_plan_s.clear();
}
return pm_dn_plan_s;
}