http://demo.gcpowertools.com.cn/spreadjs/exceliosample/exceliosample/
Java實現導入Excel:
1、做一個jsp頁面,頁面包括瀏覽文件,提交文件
2、將excel文件上傳到服務器
3、 服務器對該excel文件進行讀出
4、 將excel文件內容顯示到頁面上
環境搭建:
需要准備的包:commons-fileupload-1.2.1.jar & commons-io-1.3.2.jar 這兩個包是上傳用的
jxl.jar 這個包是讀取excel用的 下載地址 :http://sourceforge.net/projects/jexcelapi/ 建議不要用新版本,因為新版本會出現與jdk版本兼容問題,如果運行程序出現問題的時候請切換舊版本。
一、Jsp頁面
注意:1、在jsp頁面的form要使用html本身的
標記,而不要使用第三方視圖開源框架的form標記,例如不要使用strut的。
2、在
的屬性里必須加上 ENCTYPE="multipart/form-data"
<</SPAN>hr>
<</SPAN>form action="importExcel" method="post" enctype="multipart/form-data">
<</SPAN>input type="file" name="importExcel" id="importExcel">
<</SPAN>input type="submit" value="導入">
</</SPAN>form>
二、上傳excel的Servlet
注意:1、導入的excel最好用后綴為.xls,如果用.xlsx可能會導不進去。
2、在調用FileItem的write方法前必須保證文件的存放路徑存在否則出現異常。commons fileupload不會自動為你建立不存在的目錄。
3、上傳后會對文件進行重命名,以時間為文件名進行命名
public class ImportExcelServlet extends HttpServlet {
//緩沖區域
File tempPathFile;
//默認路徑
String uploadTo = "D:\\";
// 支持的文件類型
String[] errorType = { ".xls" };
//格式化日期
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//取得服務器真實路徑
uploadTo = req.getSession().getServletContext().getRealPath("\\") + "upload\\";
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置緩沖區大小,這里是4kb
factory.setSizeThreshold(4096);
// 設置緩沖區目錄
factory.setRepository(tempPathFile);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
// 設置最大文件尺寸,這里是4MB
upload.setSizeMax(4*1024*1024);
// 開始讀取上傳信息
List fileItems = new ArrayList();
try {
fileItems = upload.parseRequest(req);
} catch (FileUploadException e1) {
e1.printStackTrace();
}
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
System.out.println("fileItems的大小是" + fileItems.size());
// 正則匹配,過濾路徑取文件名
String regExp = ".+\\\\(.+)$";
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表單信息
System.out.println("正在處理" + item.getFieldName());
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
boolean flag = false;
for (int temp = 0; temp < errorType.length; temp++) {
if(m.group(1).endsWith(errorType[temp])) {
flag = true;
}
}
if(!flag) {
System.out.println("上傳了不支持的文件類型");
throw new IOException(name + ": wrong type");
}
try {
String fileName = uploadTo + format.format(new Date()) + m.group(1).substring(m.group(1).indexOf("."));
item.write(new File(fileName));
//調用ReadExcel類進行讀出excel
ReadExcel.readExcel(fileName, resp.getWriter());
System.out.println(name + "\t\t" + size);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
// 這里添加對不是上傳文件表單項的處理
System.out.println("這是一個表單項");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
public void init() throws ServletException {
tempPathFile = new File("d:\\temp\\buffer\\");
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
三、讀出excel文件內容的類
public class ReadExcel {
public static void readExcel(String pathname, PrintWriter out) {
try {
//打開文件
Workbook book = Workbook.getWorkbook(new File(pathname)) ;
//取得第一個sheet
Sheet sheet = book.getSheet(0);
//取得行數
int rows = sheet.getRows();
for(int i = 0; i < rows; i++) {
Cell [] cell = sheet.getRow(i);
for(int j=0; j
//getCell(列,行)
out.print(sheet.getCell(j, i).getContents());
out.print(" ");
}
out.println("
");
}
//關閉文件
book.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
總結:上面只是一個很簡單的導入excel文件的例子,如果想做完善還得下更多的功夫。在做的過程中如果出現Workbook打不開,請更換jxl版本,盡量用低版本,這樣與jdk兼容會好點
