我们也可以使用简单和最好的方法 2 将 Excel 表上传到数据库
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./ExcelSample" method="post" id="formdata"
enctype="multipart/form-data" onsubmit="return excelUpload('Conform')">
<label for="inputSuccess2" class="control-label">
<div id="scn">Select Excel File</div>
</label> <input type="file" name="excel" id="excelfile"
class="form-control active"> <label class="control-label"> </label>
<input type="submit" class="form-control btn btn-orange" id="Upload"
value="Upload"></form>
</body>
</html>
package com.excel.Sample.ExcelAnn;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.METHOD)
public @interface ExcelColumn {
boolean ignore() default false;
String label() default "";
}
package com.excel.Sample.ExcelAnn;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.TYPE)
public @interface ExcelReport {
String reportName();
}
package com.excel.Sample.Actions;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.excel.Sample.ExcelAnn.ExcelColumn;
import com.excel.Sample.ExcelAnn.ExcelReport;
public class ExcelAction {
private HSSFWorkbook workbook = null;
private String workbookName = "Book1.xls";
private Map<String, String> fieldLabelMap = new HashMap<String, String>();
private List<String> orderLabels = new ArrayList<String>();
private CellStyle columnHeaderCellStyle = null;
public ExcelAction() {
initialize();
}
private void initialize() {
setWorkbook(new HSSFWorkbook());
setColumnHeaderCellStyle(createColumnHeaderCellStyle());
}
private CellStyle createColumnHeaderCellStyle() {
CellStyle cellStyle = getWorkbook().createCellStyle();
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT()
.getIndex());
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
return cellStyle;
}
public void closeWorksheet() {
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream(getWorkbookName());
getWorkbook().write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private HSSFSheet getSheetWithName(String name) {
HSSFSheet sheet = workbook.getSheet(name);
return sheet;
}
private void initializeForRead(InputStream inp) throws IOException {
workbook = new HSSFWorkbook(inp);
}
private <T> void processAnnotations(T object) {
Class<?> clazz = object.getClass();
ExcelReport reportAnnotation = (ExcelReport) clazz
.getAnnotation(ExcelReport.class);
for (Method method : clazz.getMethods()) {
ExcelColumn excelColumn = method.getAnnotation(ExcelColumn.class);
if ((excelColumn != null) && !excelColumn.ignore()) {
getFieldLabelMap().put(excelColumn.label(), method.getName());
getOrderLabels().add(excelColumn.label());
}
}
}
@SuppressWarnings("unchecked")
public <T> List<T> readData(String classname, InputStream inp)
throws Exception {
Class clazz = Class.forName(classname);
processAnnotations(clazz.newInstance());
initializeForRead(inp);
HSSFSheet sheet = getSheetWithName("Sheet1");
List<T> result = new ArrayList<T>();
Map<String, String> mp = new HashMap<String, String>();
Iterator<Row> rowIterator = sheet.rowIterator();
int rowCount = 0;
while (rowIterator.hasNext()) {
T one = (T) clazz.newInstance();
try {
int colCount = 0;
result.add(one);
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (rowCount == 0) {
mp.put(colCount + "", cell.getStringCellValue()
.toString().trim());
} else {
int type = cell.getCellType();
String labelName = mp.get(colCount + "");
String getter = getFieldLabelMap().get(labelName);
String fieldName = getter.substring(3);
fieldName = decapitalize(fieldName);
Method method = constructMethod(clazz, fieldName);
if (type == 1) {
String value = cell.getStringCellValue();
Object[] values = new Object[1];
values[0] = value;
method.invoke(one, values);
} else if (type == 0) {
Double num = cell.getNumericCellValue();
Class<?> returnType = getGetterReturnClass(clazz,
fieldName);
if (returnType == Integer.class) {
method.invoke(one,(Integer) num.intValue());
} else if (returnType == Double.class) {
method.invoke(one, (Integer) num.intValue());
} else if (returnType == Float.class) {
method.invoke(one, num.floatValue());
} else if (returnType == Date.class) {
method.invoke(one, cell.getDateCellValue());
}
} else if (type == 3) {
double num = cell.getNumericCellValue();
Object[] values = new Object[1];
values[0] = num;
method.invoke(one, values);
}
}
colCount++;
}
} catch (Exception e) {
System.out.println(e);
}
rowCount++;
}
return result;
}
private Class<?> getGetterReturnClass(Class<?> clazz, String fieldName) {
String methodName = "get" + capitalize(fieldName);
Class<?> returnType = null;
for (Method method : clazz.getMethods()) {
if (method.getName().equals(methodName)) {
returnType = method.getReturnType();
break;
}
}
return returnType;
}
@SuppressWarnings("unchecked")
private Method constructMethod(Class clazz, String fieldName)
throws SecurityException, NoSuchMethodException {
Class<?> fieldClass = getGetterReturnClass(clazz, fieldName);
return clazz.getMethod("set" + capitalize(fieldName), fieldClass);
}
public <T> void writeReportToExcel(List<T> data) throws Exception {
processAnnotations(data.get(0));
Sheet sheet = getWorkbook().createSheet(
data.get(0).getClass().getName());
int rowCount = 0;
int columnCount = 0;
Row row = sheet.createRow(rowCount++);
for (String labelName : getOrderLabels()) {
Cell cel = row.createCell(columnCount++);
cel.setCellValue(labelName);
cel.setCellStyle(getColumnHeaderCellStyle());
}
Class<? extends Object> classz = data.get(0).getClass();
for (T t : data) {
row = sheet.createRow(rowCount++);
columnCount = 0;
for (String label : getOrderLabels()) {
String methodName = getFieldLabelMap().get(label);
Cell cel = row.createCell(columnCount);
Method method = classz.getMethod(methodName);
Object value = method.invoke(t, (Object[]) null);
if (value != null) {
if (value instanceof String) {
cel.setCellValue((String) value);
} else if (value instanceof Long) {
cel.setCellValue((Long) value);
} else if (value instanceof Integer) {
cel.setCellValue((Integer) value);
} else if (value instanceof Double) {
cel.setCellValue((Double) value);
}
}
columnCount++;
}
}
}
public Map<String, String> getFieldLabelMap() {
return fieldLabelMap;
}
public void setFieldLabelMap(Map<String, String> fieldLabelMap) {
this.fieldLabelMap = fieldLabelMap;
}
public List<String> getOrderLabels() {
return orderLabels;
}
public void setOrderLabels(List<String> orderLabels) {
this.orderLabels = orderLabels;
}
public String capitalize(String string) {
String capital = string.substring(0, 1).toUpperCase();
return capital + string.substring(1);
}
public String decapitalize(String string) {
String capital = string.substring(0, 1).toLowerCase();
return capital + string.substring(1);
}
public String getWorkbookName() {
return workbookName;
}
public void setWorkbookName(String workbookName) {
this.workbookName = workbookName;
}
void setWorkbook(HSSFWorkbook workbook) {
this.workbook = workbook;
}
Workbook getWorkbook() {
return workbook;
}
public CellStyle getColumnHeaderCellStyle() {
return columnHeaderCellStyle;
}
public void setColumnHeaderCellStyle(CellStyle columnHeaderCellStyle) {
this.columnHeaderCellStyle = columnHeaderCellStyle;
}
}
package com.excel.Sample.Model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.excel.Sample.ExcelAnn.ExcelColumn;
@Entity
@Table(name = "directory")
public class Directory {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "Test_Name")
private String name;
@Column(name = "Path", nullable = false)
private String path;
@Column(name = "Directory", nullable = false)
private String directory;
@Column(name = "ContainedFiles", nullable = false)
private Integer containedFiles;
@Column(name = "DateFormate", nullable = false)
private Date dateFormate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ExcelColumn(label = "Test Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ExcelColumn(label = "Path")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@ExcelColumn(label = "Directory")
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
@ExcelColumn(label = "ContainedFiles")
public Integer getContainedFiles() {
return containedFiles;
}
public void setContainedFiles(Integer containedFiles) {
this.containedFiles = containedFiles;
}
@ExcelColumn(label = "DateFormate")
public Date getDateFormate() {
return dateFormate;
}
public void setDateFormate(Date dateFormate) {
this.dateFormate = dateFormate;
}
}
package com.excel.Sample.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.excel.Sample.Actions.ExcelAction;
import com.excel.Sample.Model.Directory;
import com.excel.util.HibernateUtil;
/**
* Servlet implementation class ExcelSample
*/
public class ExcelSample extends HttpServlet {
private static final long serialVersionUID = 1L;
public static String modelName = "com.excel.Sample.Model.Directory";
/**
* @see HttpServlet#HttpServlet()
*/
public ExcelSample() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.getMessage();
}
FileItem item = (FileItem) items.get(0);
try {
ExcelAction ea = new ExcelAction();
List<Directory> e = ea.readData(modelName, item
.getInputStream());
out.println("<table>");
for (int i = 1; i < e.size(); i++) {
Directory ex = (Directory) e.get(i);
Session session = HibernateUtil.getSessionFactory()
.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(ex);
transaction.commit();
} catch (HibernateException exp) {
transaction.rollback();
exp.printStackTrace();
} finally {
session.close();
}
String date = new SimpleDateFormat("dd/MM/yyyy")
.format(ex.getDateFormate());
out.println("<tr><td>" + ex.getContainedFiles()
+ " </td><td> " + ex.getDirectory()
+ " </td><td> " + ex.getPath() + " </td><td> "
+ ex.getName() + "</td><td> " + date
+ "</td></tr>");
}
out.println("</table>");
} catch (Exception e) {
System.out.println(e);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
- Excel For Mate 如下
测试名称路径目录 ContainedFiles DateFormate .settings /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/.settings 目录 1 5/2/2013 src /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/src 目录 1 12/3 /2013 .classpath1 /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/.classpath1 file1 1 11/4/2013 测试 /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/test 目录 1 3/5/2013 测试。 xls /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/test.xls 文件 11 6/6/2013 .project /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/.project 文件 1 12/7/2013 bin / home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/bin 目录 1 6/8/2013