您的位置:首页 > 运维架构 > Apache

关于apache POI excel文件导入导出

2017-11-05 16:12 357 查看



首先得上传文件

引入jquery.ocupload-1.1.2.js

$("#button-import").upload({
name: 'upload', // <input name="file" />
action: '${pageContext.request.contextPath}/importSubarea.action', // 提交请求action路径
enctype: 'multipart/form-data', // 编码格式
autoSubmit: true, // 选中文件提交表单
onComplete: function(response) {// 请求完成时 调用函数
if(response=="success"){
alert("数据导入成功!");
}
}
});

点击导入按钮的时候,插件的upload这个插件可以实现不做页面跳转的功能。
@Controller
@Scope("prototype")
public class RegionAction extends BaseAction<Region>{
//接收上传的文件
private File myFile;
public void setMyFile(File myFile) {
this.myFile = myFile;
}

/**
* 批量导入
* @throws IOException
* @throws FileNotFoundException
*/
public String importXls() throws Exception{
String flag = "1";
//使用POI解析Excel文件
try{
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(myFile));
//获得第一个sheet页
HSSFSheet sheet = workbook.getSheetAt(0);
List<Region> list = new ArrayList<Region>();
for (Row row : sheet) {
int rowNum = row.getRowNum();
if(rowNum == 0){
//第一行,标题行,忽略
continue;
}
String id = row.getCell(0).getStringCellValue();
String province = row.getCell(1).getStringCellValue();
String city = row.getCell(2).getStringCellValue();
String district = row.getCell(3).getStringCellValue();
String postcode = row.getCell(4).getStringCellValue();
Region region = new Region(id, province, city, district, postcode, null, null, null);

city = city.substring(0, city.length() - 1);
String[] stringToPinyin = PinYin4jUtils.stringToPinyin(city);
String citycode = StringUtils.join(stringToPinyin, "");

//简码---->>HBSJZCA
province = province.substring(0, province.length() - 1);
district = district.substring(0, district.length() - 1);
String info = province + city + district;//河北石家庄长安
String[] headByString = PinYin4jUtils.getHeadByString(info);
String shortcode = StringUtils.join(headByString, "");

region.setCitycode(citycode);
region.setShortcode(shortcode);
list.add(region);
}
regionService.saveBatch(list);
}catch (Exception e) {
flag = "0";
}
ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
ServletActionContext.getResponse().getWriter().print(flag);
return NONE;
}

如上所示,通过poi创建表格对象,便利行,获取数据,插入到数据库。以上excel文件的导入方式。
接下来就是要将文件的导出方式了

/**
* 使用POI写入Excel文件,提供下载
* @throws IOException
*/
public String exportXls() throws IOException {
List<Subarea> list = subareaService.findAll();
// 在内存中创建一个Excel文件,通过输出流写到客户端提供下载
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建一个sheet页
HSSFSheet sheet = workbook.createSheet("分区数据");
// 创建标题行
HSSFRow headRow = sheet.createRow(0);
headRow.createCell(0).setCellValue("分区编号");
headRow.createCell(1).setCellValue("区域编号");
headRow.createCell(2).setCellValue("地址关键字");
headRow.createCell(3).setCellValue("省市区");

for (Subarea subarea : list) {
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(subarea.getId());
dataRow.createCell(1).setCellValue(subarea.getRegion().getId());
dataRow.createCell(2).setCellValue(subarea.getAddresskey());
Region region = subarea.getRegion();
dataRow.createCell(3).setCellValue(region.getProvince()+region.getCity()+region.getDistrict());
}

String filename = "分区数据.xls";
String agent = ServletActionContext.getRequest().getHeader("User-Agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
//一个流两个头
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
String contentType = ServletActionContext.getServletContext().getMimeType(filename);
ServletActionContext.getResponse().setContentType(contentType);
ServletActionContext.getResponse().setHeader("content-disposition", "attchment;filename="+filename);
workbook.write(out);
return NONE;
}

文件编码
public class FileUtils {
/**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public static String encodeDownloadFilename(String filename, String agent)
throws IOException {
if (agent.contains("Firefox")) { // 火狐浏览器
filename = "=?UTF-8?B?"
+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
+ "?=";
filename = filename.replaceAll("\r\n", "");
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+"," ");
}
return filename;
}
}


如上所示就是apache poi直接操作excel的文件上传下载方式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: