使用poi导入导出数据库表数据网上已经有很多例子了,在这里,把自己做的记录下来,方便以后使用。
首先在poi官网http://poi.apache.org/download.html下载最新版本的poi组件,然后把jar包放到web工程的lib下
先说poi导入excel数据到数据库吧,这里只支持excel2003,excel2007导入。我是这样处理的,这其实包括2个部分,一个是excel文件上传,一个是对上传的excel文件解析,并吧数据保存到数据库中。
通用的poi解析excel2003或者2007代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
/**
* 对外提供读取excel 的方法
* */
public static List<List<Object>> readExcel(File file) throws IOException{
String fileName = file.getName();
String extension = fileName.lastIndexOf(".")==-1?"":fileName.substring(fileName.lastIndexOf(".")+1);
if("xls".equals(extension)){
return read2003Excel(file);
}else if("xlsx".equals(extension)){
return read2007Excel(file);
}else{
throw new IOException("不支持的文件类型");
}
}
/**
* 读取 office 2003 excel
* @throws IOException
* @throws FileNotFoundException */
private static List<List<Object>> read2003Excel(File file) throws IOException{
List<List<Object>> list = new LinkedList<List<Object>>();
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = hwb.getSheetAt(0);
Object value = null;
HSSFRow row = null;
HSSFCell cell = null;
for(int i = sheet.getFirstRowNum();i<= sheet.getPhysicalNumberOfRows();i++){
row = sheet.getRow(i);
if (row == null) {
continue;
}
List<Object> linked = new LinkedList<Object>();
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
continue;
}
DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
// System.out.println(i+"行"+j+" 列 is String type");
value = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
// System.out.println(i+"行"+j+" 列 is Number type ; DateFormt:"+cell.getCellStyle().getDataFormatString());
if("@".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
} else if("General".equals(cell.getCellStyle().getDataFormatString())){
value = nf.format(cell.getNumericCellValue());
}else{
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
// System.out.println(i+"行"+j+" 列 is Boolean type");
value = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
// System.out.println(i+"行"+j+" 列 is Blank type");
value = "";
break;
default:
// System.out.println(i+"行"+j+" 列 is default type");
value = cell.toString();
}
if (value == null || "".equals(value)) {
continue;
}
linked.add(value);
}
list.add(linked);
}
return list;
}
/**
* 读取Office 2007 excel
* */
private static List<List<Object>> read2007Excel(File file) throws IOException {
List<List<Object>> list = new LinkedList<List<Object>>();
// 构造 XSSFWorkbook 对象,strPath 传入文件路径
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
Object value = null;
XSSFRow row = null;
XSSFCell cell = null;
for (int i = sheet.getFirstRowNum(); i <= sheet
.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
List<Object> linked = new LinkedList<Object>();
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
continue;
}
DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
// System.out.println(i+"行"+j+" 列 is String type");
value = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
// System.out.println(i+"行"+j+" 列 is Number type ; DateFormt:"+cell.getCellStyle().getDataFormatString());
if("@".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
} else if("General".equals(cell.getCellStyle().getDataFormatString())){
value = nf.format(cell.getNumericCellValue());
}else{
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
// System.out.println(i+"行"+j+" 列 is Boolean type");
value = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
// System.out.println(i+"行"+j+" 列 is Blank type");
value = "";
break;
default:
// System.out.println(i+"行"+j+" 列 is default type");
value = cell.toString();
}
if (value == null || "".equals(value)) {
continue;
}
linked.add(value);
}
list.add(linked);
}
return list;
}
public static void main(String[] args) throws IOException
{
File file = new File("d:\\test1.xlsx");
List<List<Object>> list= readExcel(file);
// System.out.println(list);
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.lee.common.poi.ExcelReader;
import com.opensymphony.xwork2.ActionSupport;
public class ImportExcelAction extends ActionSupport{
@Autowired
CustomerService customerService ;
// 上传文件域
private File excel;
// 上传文件类型
private String excelContentType;
// 封装上传文件名
private String excelFileName;
// 接受依赖注入的属性
private String savePath;
public String execute() throws Exception
{
clearErrorsAndMessages();
FileOutputStream fos = null;
FileInputStream fis = null;
try{
//防止文件重名,用系统时间,精确到毫秒为文件命名
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat( "yyyyMMddHHmmssSSS");//取系统时间,精确到毫秒。
java.util.Date date = new java.util.Date();
String strTime = simpleDateFormat.format(date);
excelFileName = strTime+getExcelFileName();
fos = new FileOutputStream(getSavePath() + "/" + excelFileName);
fis = new FileInputStream(getExcel());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
// System.out.println("文件上传成功");
} catch (Exception e) {
// System.out.println("文件上传失败");
e.printStackTrace();
addActionError("文件上传失败");
return "input";
} finally {
close(fos, fis);
}
try {
List<List<Object>> list= ExcelReader.readExcel(new File(getSavePath() + "/" + excelFileName));
//在这里默认excel有表头数据,其实就是list第一行,所以i从1开始
if(!(list.size()<1) ){
for(int i=1 ;i<list.size();i++)
{
//通过 (String)list.get(i).get(0),(String)list.get(i).get(1)这种方式获取相应的值
//并新建对象,把数据持久化到数据库中
}
}
else
{
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
addActionError("解析excel失败");
return "input";
}
return SUCCESS;
}
private void close(FileOutputStream fos, FileInputStream fis) {
if (fis != null) {
try {
fis.close();
fis=null;
} catch (IOException e) {
// System.out.println("FileInputStream关闭失败");
e.printStackTrace();
}
}
}
/**
* 文件存放目录
*
* @return
*/
public String getSavePath() throws Exception{
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getExcel() {
return excel;
}
public void setExcel(File excel) {
this.excel = excel;
}
public String getExcelContentType() {
return excelContentType;
}
public void setExcelContentType(String excelContentType) {
this.excelContentType = excelContentType;
}
public String getExcelFileName() {
return excelFileName;
}
public void setExcelFileName(String excelFileName) {
this.excelFileName = excelFileName;
}
}
struts.xml配置
<action name="importExcel"
class="importExcelAction">
<param name="savePath">/excelfolder</param>
<result name="success">/WEB-INF/view/importExcelSuccess.jsp</result>
<result name="input">/WEB-INF/view/importCustomerInfo.jsp</result>
</action>
相应 的jsp页面
<script>
function check()
{
var excelfileName = document.upload_form.excel.value ;
var exceltype = excelfileName.substring(excelfileName.lastIndexOf('.') + 1).toLowerCase();
if(excelfileName.length==0)
{
alert("请选择excel");
return false;
}
else if(!(exceltype=="xls"|| exceltype=="xlsx"))
{
alert("格式必须为excel 2003或者2007的一种");
return false;
}
}
</script>
<form name="upload_form" action="importExcel.action" method="post" enctype="multipart/form-data" onsubmit="return check()">
<br>
<input type="file" id="excel" name="excel" size="29" class="file">
<br>
<br>
<input type="submit" class="importButton" value="">
至于poi导出excel报表,也比较容易,参见我以前写的例子 http://download.csdn.net/detail/xiaoliouc/5117319