java+poi读取和存储excel表格内容
2015-07-28 10:00
393 查看
以下是在java开发中经常使用的poi读取excel表格内容和写入excel表格,只需修改对应的实体类和行列就能使用。
记得导入poi架包
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
Student
private Integer id;
private String name,address;
//提供get/set方法
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
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.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import bean.Student;
public class ExcelFileUtil {
/**
*
* @方法功能说明: 读取用户导入的Excel数据 //可以依据实际情况修改
* @修改者名字:yang
* @修改日期 : 2015-7-28
* @修改内容 :
* @参数: @param file
* @return void
* @throws Exception
* @异常抛出:
*/
public static List readExcel(File file) throws Exception {
Workbook wb = null;
List list = new ArrayList();
Student student = null;
try {
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
if (fileName.endsWith(“xls”)) {
wb = new HSSFWorkbook(inputStream); // 解析xls格式
} else if (fileName.endsWith(“xlsx”)) {
wb = new XSSFWorkbook(inputStream); // 解析xlsx格式
}
Sheet sheet = wb.getSheetAt(0); // 第一个工作表
/* path = sb.append(UrlInfo.URL_EXCEL + fileName+new SimpleDateFormat(“yyyy-MM-dd_HH-mm-ss”).format(new java.util.Date())+”.xls”); 最好以活动名称和时间作为文件名,UrlInfo.URL_EXCEL代表存放路径,由于文件名称不能有转义等特殊字符,所以日期时间不能用yyyy-MM-dd_HH:mm:ss命名/
path = sb.append(UrlInfo.URL_EXCEL + fileName+”.xls”); //最好以名称和时间作为文件名,避免重复
FileOutputStream fout = new FileOutputStream(path.toString());
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
return path.toString();
}
}
记得导入poi架包
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
Student
private Integer id;
private String name,address;
//提供get/set方法
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
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.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import bean.Student;
public class ExcelFileUtil {
/**
*
* @方法功能说明: 读取用户导入的Excel数据 //可以依据实际情况修改
* @修改者名字:yang
* @修改日期 : 2015-7-28
* @修改内容 :
* @参数: @param file
* @return void
* @throws Exception
* @异常抛出:
*/
public static List readExcel(File file) throws Exception {
Workbook wb = null;
List list = new ArrayList();
Student student = null;
try {
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
if (fileName.endsWith(“xls”)) {
wb = new HSSFWorkbook(inputStream); // 解析xls格式
} else if (fileName.endsWith(“xlsx”)) {
wb = new XSSFWorkbook(inputStream); // 解析xlsx格式
}
Sheet sheet = wb.getSheetAt(0); // 第一个工作表
int firstRowIndex = sheet.getFirstRowNum() + 1; // 得到第一行的下标,此处加2目的是为了避免读取活动首行 int lastRowIndex = sheet.getLastRowNum(); // 得到最后一行的下标 ,他们之差代表总行数 // 循环读取数据 for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { Row row = sheet.getRow(rIndex); int firstCellIndex = row.getFirstCellNum(); // 得到第一列 int lastCellIndex = row.getLastCellNum(); // 得到最后一列,他们之差是总列数 int index = 0; // 作为控制读取的变量 Student = new Student(); // 每次循环新建一个对象接收 for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { Cell cell = row.getCell(cIndex); if (cell != null) { if (index == 0) { //如果读取的数据有科学计数法,如:1.2322E5,那么需要处理 String num="1.2322E5"; System.out.println(new BigDecimal(num).toPlainString()); Student.setId(cell.toString().replace(".0",""));//替换读取后自动类型转换而导致的问题。读取id index++; } else if (index == 1) { Student.setName(cell.toString()); //读取姓名 index++; } else if(index==2){ Student.setAddress(cell.toString()); //读取地址 index=0; } }else { index++; continue;//如果有空,直接跳过本行,进入读取下一行数据 } // System.out.print(cell+" "); } list.add(Student);// 循环完成一次则将一个对象放入集合一次,直到循环结束 } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return list; } /** * * @方法功能说明:将读取的内容写入excel文件,然后保存 * @修改者名字:yang * @修改日期 : 2015-7-9 * @修改内容 : * @参数: @param list,fileName * @参数: @return * @return String * @异常抛出: */ public static String wirteExcel(List<Student> list,String fileName) { StringBuffer sb = null; StringBuffer path =null; HSSFRow row = null; // 第一步,创建一个webbook,对应一个Excel以xsl为扩展名文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet("统计表"); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); // HSSFDataFormat dataFormat = wb.createDataFormat();日期转换,可以不用 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell(0); cell.setCellValue("学生id"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("学生名字"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("地址"); cell.setCellStyle(style); cell = row.createCell(3); // 第五步,写入实体数据 实际应用中这些数据从数据库得到, for (int i=0;i<list.size();i++) { row = sheet.createRow((int) i + 1); Student student=list.get(i); // 第四步,创建单元格,并设置值 row.createCell(0).setCellValue(student.getId()); row.createCell(1).setCellValue(student.getName()); row.createCell(2).setCellValue(student.getAddress()); cell = row.createCell(3); } } // 第六步,将文件存到指定位置 try { sb = new StringBuffer();
/* path = sb.append(UrlInfo.URL_EXCEL + fileName+new SimpleDateFormat(“yyyy-MM-dd_HH-mm-ss”).format(new java.util.Date())+”.xls”); 最好以活动名称和时间作为文件名,UrlInfo.URL_EXCEL代表存放路径,由于文件名称不能有转义等特殊字符,所以日期时间不能用yyyy-MM-dd_HH:mm:ss命名/
path = sb.append(UrlInfo.URL_EXCEL + fileName+”.xls”); //最好以名称和时间作为文件名,避免重复
FileOutputStream fout = new FileOutputStream(path.toString());
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
return path.toString();
}
}
相关文章推荐
- Spring MVC+Mybatis+Maven+Velocity+Mysql
- eclipse 开发playframework
- java多线程
- java 判断三个字符串中是否有相等,去掉重复字符串输出
- javaweb-url /
- springmvc缓存
- 打开eclipse 异常弹出对话框 Subversion Native Library Not Available的解决
- iOS注释标记(参考javadoc)
- 简单的Java打字游戏
- [Java]对字符串中的每个单词个数进行统计
- java常用的23种设计模式《转》
- java playframework
- Java对数组的复制
- 我的Java开发学习之旅------>Base64的编码思想以及Java实现
- draw something in Java DEMO
- java 对象序列化和对象反序列化操作时的版本兼容性问题
- 设置Eclipse中的tab键为4个空格的完整方法
- Java会话(session)管理
- Java抽象类应用—模板方法模式
- Java中isAssignableFrom()方法与instanceof()方法用法