1、jsp代码:
<div style="margin-bottom:10px;">
<input type="file" name="filedata" id="file" multiple/>
<input type="button" value="上传" id="fileBtn"/>
</div>
<div style="margin-bottom:10px;">
款项审核页-数据导出为excel-数据格式.xlsx<a id="downBtn1" href="">下载1</a><input type="button" value="下载2" id="downBtn2"/>
</div>
$("#fileBtn").click(function() {
//获取上传图片的文件名
var confirmfileImageName =$("#file").val();
//员工是否选择了图片
if(confirmfileImageName!=""){
$.ajaxFileUpload({
url:'ExcelReadAction',
secureuri:false,
fileElementId:'file',//file标签的id
dataType: 'json',//返回数据的类型
data:{},//一同上传的数据
success: function (ret) {alert("上传成功");
}
});
} else {
}
})
$("#downBtn1").attr("href","/file/款项审核页-数据导出为excel-数据格式.xlsx");
$("#downBtn2").click(function() {
$.ajaxFileUpload({
url:'ExcelWriteAction',
secureuri:false,
fileElementId:'file',//file标签的id
dataType: 'json',//返回数据的类型
data:{},//一同上传的数据
success: function (ret) {alert("上传成功");
}
});
})
2、struts配置
<!-- excel读取 -->
<action name="ExcelReadAction" class="com.dld.app.sales.action.ExcelOperateAction" method="excelRead">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
</action>
<!-- excel下载 -->
<action name="ExcelWriteAction" class="com.dld.app.sales.action.ExcelOperateAction" method="excelWrite">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
</action>
3、action代码:
package com.dld.app.sales.action;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.write.WriteException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSONObject;
import com.dld.platform.client.ServiceClientFactory;
import com.dld.platform.data.DatasetFactory;
import com.dld.platform.data.Record;
import com.dld.platform.model.BaseModelFactory;
import com.dld.platform.model.RequestModel;
import com.dld.platform.model.ResponseModel;
public class ExcelOperateAction {
private File[] filedata; // 文件
private String[] filedataFileName; // 文件名
private String contractNum;
/**
* 文件上传
*
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public String excelRead() throws IOException, InvalidFormatException {
HttpServletRequest request = ServletActionContext.getRequest();
request.setCharacterEncoding("utf-8");
Map<String,Object> shopMap = new HashMap<String,Object>();
List<Map<String,Object>> shopMapList=new ArrayList<Map<String,Object>>();
if (this.filedata != null) {
File excel = this.getFiledata()[0];
Workbook workbook = WorkbookFactory.create(excel);
// 遍历excel页
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
// 遍历行
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row != null) {
Record record = DatasetFactory.buildRecord();
Cell shopNo = row.getCell(0);
record.addCell("shopNo", getValue(shopNo));
Cell shopName = row.getCell(1);
record.addCell("shopName", getValue(shopName));
shopMapList.add(record.toMap());
}
}
}
shopMap.put("shopMapList", shopMapList);
}
RequestModel shopMapRequest=BaseModelFactory.buildRequestModel("sales_readExcelForShop",
DatasetFactory.buildDatasetByRecord(new String[]{"shopMapStr"}, new Object[]{JSONObject.toJSONString(shopMap)}));
ResponseModel shopMapResponse=ServiceClientFactory.getServiceClient().doRequestResponse(shopMapRequest);
if(!shopMapResponse.isSuccess()){
return null;
}
return null;
}
/**
* 文件下载
*
* @return
* @throws FileNotFoundException
* @throws IOException
* @throws InvalidFormatException
* @throws WriteException
*/
public String excelWrite() throws InvalidFormatException, IOException {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");// 解决中文乱码
File file = new File(request.getSession().getServletContext().getRealPath("/") + "/file/款项审核页-数据导出为excel-数据格式.xlsx");
// 商户模版
Workbook book = WorkbookFactory.create(file);
Sheet sheet = book.getSheetAt(0);
Cell cell = sheet.createRow(3).createCell(1);
cell.setCellValue("是");
// 修改模板内容导出新模板
FileOutputStream out = new FileOutputStream("d:/a.xlsx");
book.write(out);
book.close();
out.close();
return null;
}
@SuppressWarnings("static-access")
private String getValue(Cell cell) {
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
// 返回数值类型的值
return String.valueOf(cell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(cell.getStringCellValue());
}
}
/**
* 附件下载
*
* @return
*/
public String downloadFile() {
return null;
}
public static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
public File[] getFiledata() {
return filedata;
}
public void setFiledata(File[] filedata) {
this.filedata = filedata;
}
public String[] getFiledataFileName() {
return filedataFileName;
}
public void setFiledataFileName(String[] filedataFileName) {
this.filedataFileName = filedataFileName;
}
public String getContractNum() {
return contractNum;
}
public void setContractNum(String contractNum) {
this.contractNum = contractNum;
}
}
文件和文件名变量必须和jsp里面的name名称对应,struts能利用值桟进行相应map,获取到相应数据
private File[] filedata; // 文件
private String[] filedataFileName; // 文件名