apache POI技术的使用
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
下载开发包:
解压上面的zip文件:
在项目中引入POI的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
POI使用:使用POI读取Excel的数据
package com.test.bos.test; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.junit.Test; public class POITest { @Test
public void test() throws FileNotFoundException, IOException{
String filePath = "E:\\区域导入测试数据.xls";
//包装一个Excel文件对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(new File(filePath)));
//读取文件中第一个Sheet标签页
HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
//遍历标签页中所有的行
for (Row row : sheetAt) {
System.out.println();//换行
//遍历行中的所有单元格
for (Cell cell : row) {
String value = cell.getStringCellValue();
System.out.print(value);
}
}
}
}
POI结合OCUpload的使用
package com.test.bos.web.action; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import javax.annotation.Resource; import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller; import com.test.bos.domain.Region;
import com.test.bos.service.IRegionService;
import com.test.bos.web.action.base.BaseAction; /**
* 区域管理
*
* @author jepson
*
*/
@Controller("regionAction")
@Scope("prototype")
public class RegionAction extends BaseAction<Region> {
@Resource(name="regionService")
private IRegionService regionService;
// 属性驱动,接收上传的文件
private File regionFile; public void setRegionFile(File regionFile) {
this.regionFile = regionFile;
} List<Region> regionList = new ArrayList<Region>();
/**
* 区域导入
* @throws IOException
* @throws FileNotFoundException
*/
public String importXls() throws Exception {
//包装一个excel文件对象
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(regionFile));
//读取文件中第一个sheet标签页
HSSFSheet sheet = workbook.getSheet("Sheet1");
//遍历页面中的每一行
for (Row row : sheet) {
int rowNum = row.getRowNum();//获取行号,从0开始
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);
/*
* 这里不建议使用
* regionService.save(region);
* 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数
*/
regionList.add(region);
}
//调用service层的方法批量保存
regionService.saveBatch(regionList);
return NONE;
}
}
POI结合springmvc文件上传
@RequestMapping(value="/item/accountupload.action")
public String accountAddBatchByUploadFile(HttpServletRequest request,HttpSession session,
HttpServletResponse response, MultipartFile acountfile,Model model){ List<Account> accountList = new ArrayList<Account>();
try {
//首先应该判断一下是否上传了文件
if(!acountfile.isEmpty()){
//获取上传的文件类型判断是否是一个xls格式的文件
String contentType = acountfile.getContentType();
if(!"application/vnd.ms-excel".equals(contentType)){
model.addAttribute("uploadinfomsg", "你上传的文件类型不对");
return "uploadinfo";
}else{
//上传的文件格式正确,使用poi技术读取excel表格的数据 InputStream inputStream = acountfile.getInputStream();
//包装一个excel文件对象
HSSFWorkbook workbook = new HSSFWorkbook(inputStream); //读取文件中第一个sheet标签页
HSSFSheet sheet = workbook.getSheet("Sheet1"); //获取登录用户的id
Integer user_id = CommonUtils.getLoginUserId(session); //遍历页面中的每一行
for (Row row : sheet) {
int rowNum = row.getRowNum();//获取行号,从0开始
if(rowNum==0){ //不需要第一行数据
continue;//跳出本次循环
} String website = row.getCell(1).getStringCellValue();
String url = row.getCell(2).getStringCellValue(); String account = row.getCell(3).getStringCellValue();
String username = row.getCell(4).getStringCellValue(); String mail = row.getCell(5).getStringCellValue(); //这里需要判断一下表格的类型
//0表示是double类型的,1表示String类型
String telephone = null;
if(row.getCell(6).getCellType()==0){
Double tele = row.getCell(6).getNumericCellValue();
telephone = tele.toString();
}else{
telephone = row.getCell(6).getStringCellValue();
} //这里需要判断一下表格的类型
//0表示是double类型的,1表示String类型
String hint = null;
if(row.getCell(7).getCellType()==0){
Double h = row.getCell(7).getNumericCellValue();
hint = h.toString();
}else{
hint = row.getCell(7).getStringCellValue();
} //包装一个账户对象
Account ac = new Account(website, url, account, username, mail, telephone, hint, user_id); /*
* 这里不建议使用
* itemService.save(ac);
* 而是加入一个list的集合中,然后进行批量保持。减少打开事务的次数
*/
accountList.add(ac);
}
//调用service层的方法批量保存
itemService.saveBatch(accountList);
model.addAttribute("uploadinfomsg", "恭喜你上传成功");
return "uploadinfo";
}
}else{
model.addAttribute("uploadinfomsg", "你没有选择上传的文件");
return "uploadinfo";
} } catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("uploadinfomsg", "上传失败");
return "uploadinfo";
}
使用POI将数据写到Excel文件中
/**
* 分区数据导出功能
* @throws IOException
*/
public String exportXls() throws IOException{
//第一步:查询所有的分区数据
List<Subarea> list = subareaService.findAll(); //第二步:使用POI将数据写到Excel文件中
//在内存中创建一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个标签页
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("位置信息");
headRow.createCell(4).setCellValue("省市区"); //遍历list集合
for (Subarea subarea : list) {
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(subarea.getId());
dataRow.createCell(1).setCellValue(subarea.getStartnum());
dataRow.createCell(2).setCellValue(subarea.getEndnum());
dataRow.createCell(3).setCellValue(subarea.getPosition());
dataRow.createCell(4).setCellValue(subarea.getRegion().getName());
} //第三步:使用输出流进行文件下载(一个流、两个头) String filename = "分区数据.xls";
String contentType = ServletActionContext.getServletContext().getMimeType(filename);
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
ServletActionContext.getResponse().setContentType(contentType); //获取客户端浏览器类型
String agent = ServletActionContext.getRequest().getHeader("User-Agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename="+filename);
workbook.write(out);
return NONE;
}
解决下载文件不同浏览器附件名的编码
package cn.itcast.bos.utils; import java.io.IOException;
import java.net.URLEncoder; import sun.misc.BASE64Encoder; 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;
}
}
使用POI将数据写到Excel中
@RequestMapping(value="/item/downloadaccount.action")
public String downloadAccount(QueryVo vo,Model model,HttpServletRequest request,
HttpServletResponse response,HttpSession session) throws Exception{ Integer userId = CommonUtils.getLoginUserId(session); vo.setUserId(userId); // 设置当前登录用户的id //查询登录用户的所有account信息
List<Account> accountList = itemService.QueryAccountList(vo); //在内存中创建一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个标签页
HSSFSheet sheet = workbook.createSheet("Sheet1"); //创建标题行
HSSFRow headRow = sheet.createRow(0);
headRow.createCell(0).setCellValue("account_id");
headRow.createCell(1).setCellValue("website");
headRow.createCell(2).setCellValue("url");
headRow.createCell(3).setCellValue("account");
headRow.createCell(4).setCellValue("username");
headRow.createCell(5).setCellValue("mail");
headRow.createCell(6).setCellValue("telephone");
headRow.createCell(7).setCellValue("hint"); //遍历list集合
for (Account ac : accountList) {
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(ac.getId());
dataRow.createCell(1).setCellValue(ac.getWebsite());
dataRow.createCell(2).setCellValue(ac.getUrl());
dataRow.createCell(3).setCellValue(ac.getAccount());
dataRow.createCell(4).setCellValue(ac.getUsername());
dataRow.createCell(5).setCellValue(ac.getMail());
dataRow.createCell(6).setCellValue(ac.getTelephone());
dataRow.createCell(7).setCellValue(ac.getHint());
}
//使用输出流进行文件下载(一个流、两个头) String filename = "account.xls";
String contentType =request.getServletContext().getMimeType(filename);
ServletOutputStream out = response.getOutputStream();
response.setContentType(contentType); //获取客户端浏览器类型
String agent = request.getHeader("User-Agent");
filename = this.encodeDownloadFilename(filename, agent);
response.setHeader("content-disposition", "attachment;filename="+filename);
workbook.write(out);
return null;
} /**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
private 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技术的使用的更多相关文章
- java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...
- java的poi技术写Excel的Sheet
在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...
- java的poi技术读,写Excel[2003-2007,2010]
在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- Apache POI 一键上传(导入excel文件到数据库)
import cn.XXXX.bos.utils.PinYin4jUtils; import org.apache.commons.lang3.StringUtils; // HSSF:操作07版本之 ...
- java的poi技术读取和导入Excel实例
本篇文章主要介绍了java的poi技术读取和导入Excel实例,报表输出是Java应用开发中经常涉及的内容,有需要的可以了解一下. 报表输出是Java应用开发中经常涉及的内容,而一般的报表往往缺乏通用 ...
- java的poi技术读取Excel数据
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- Java导出数据行写入到Excel表格:基于Apache POI
Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...
- java poi技术读取到数据库
https://www.cnblogs.com/hongten/p/java_poi_excel.html java的poi技术读取Excel数据到MySQL 这篇blog是介绍java中的poi技术 ...
随机推荐
- [转]Oracle截取字符串相关函数
转至:http://www.cnblogs.com/qmfsun/p/4493918.html 1.instr(sourceString,destString,start,appearPosition ...
- Delphi xe6 android Popup控件的使用
1.拖放Label.button和popup控件到form 2.在structure将button1和label1拖到popup1上,然后调整布局就可以 Popup有几个重要的属性: 1.Placem ...
- Others - 使用 GitHub Pages 搭建个人博客
写在前面 GitHub 是技术知识分享的地方,如果使用它写其他奇奇怪怪的东西就算了. 正文 新建一个名为 username.github.io 的 repository.其中 username 为你的 ...
- 温故而知新_C语言_递归
递归. 是的,差不多就是这种感觉.上面就是类似递归的显示表现. 2017 10 24更新: 递归这个问题放了很久.也没有写.大概是自己还没有好好理解吧. 在这里写下自己理解的全部. 一 何为递归. 字 ...
- [haut] 1281: 邪能炸弹 dp
题目描述 正在入侵艾泽拉斯的古尔丹偶然间得到了一颗邪能炸弹,经过研究,他发现这是一颗威力极其巨大且难以控制的炸弹.但是精通邪能的古尔丹突然有了一个大胆的想法,他对炸弹进行了一些小小的改造.这使得炸弹需 ...
- loj #2006. 「SCOI2015」小凸玩矩阵
#2006. 「SCOI2015」小凸玩矩阵 题目描述 小凸和小方是好朋友,小方给小凸一个 N×M N \times MN×M(N≤M N \leq MN≤M)的矩阵 A AA,要求小凸从其中选出 ...
- Linux之Vim编辑器的使用
NAME vim - Vi IMproved, a programmers text editor #vi的改进,一个程序文本编辑器 1.移动光标的方法 Ctrl+f 屏幕向下移动一页 0(数字0) ...
- plsql查询结果中文乱码
网上的教程很多,但是这里需要说明的是如果没有安装oracle客户端的情况下,该怎么修改注册表里面的oracle参数呢? 当然有些是不需要改注册表的,只需要配置环境变量就可以了,但是有的时候发现改了之后 ...
- SpriteBuilder 不能 Portrait
最近用最新的SpriteBuilder V1.3.6和Xcode 6.0.1,发现一个bug.就是在使用Xcode6的时候的SpriteBuilder已经在Project settings 里面设置了 ...
- [转载]C#实现获取浏览器信息
原文地址:C#实现获取浏览器信息作者:flywithme Request.Browser.MajorVersion.ToString();//获取客户端浏览器的(主)版本号 Request.Bro ...