---
title: "应用jxl框架进行Excel文件解析"
author: "ssqmeng"
date: "2008-11-05T09:27:00Z"
tags: ["Excel", "J#", "Servlet", "框架"]
slug: "jxl-excel"
draft: false
lastmod: "2009-01-16T13:10:00Z"
id: 317359
url: "https://ssqmeng.iteye.com/blog/317359"
---

1、在项目开发过程中需要将Excel文件导入到数据库中，应用到jxl.jar 进行解析

2、如下

01. package test;
02. import java.io.File;
03. import java.io.IOException;
04. import java.io.UnsupportedEncodingException;
05. import javax.servlet.http.HttpServletResponse;
06. import jxl.Sheet;
07. import jxl.Workbook;
08. import jxl.WorkbookSettings;
09. import jxl.read.biff.BiffException;
10. import jxl.write.Label;
11. import jxl.write.WritableSheet;
12. import jxl.write.WritableWorkbook;
13. import jxl.write.WriteException;
14. public class JxlTest {
15. public static void main(String\[] args) {
16. (new JxlTest()).excelRead();
17. }
18. public void excelRead(){
19. File file = new File("d:\\\\cicc825.xls");
20. try {
21. WorkbookSettings workbookSettings=new WorkbookSettings();
22. workbookSettings.setEncoding("ISO-8859-1"); //关键代码，解决中文乱码
23. Workbook book= Workbook.getWorkbook(file,workbookSettings);
24. //Workbook book= Workbook.getWorkbook(file);
25. Sheet sheet=book.getSheet(0);
26. int row = sheet.getRows();
27. int column =sheet.getColumns();
28. for(int i=0;i&lt;row;i++){
29. for(int j=0;j&lt;column;j++){
30. System.out.println(sheet.getCell(j, i).getContents());
31. }
32. }
33. } catch (BiffException e) {
34. e.printStackTrace();
35. } catch (IOException e) {
36. e.printStackTrace();
37. }
38. }
39. public void excelWrite(HttpServletResponse response) {
40. long time = System.currentTimeMillis();// 用当前的系统时间作为默认表名
41. String name = String.valueOf(time);
42. name ="position";
43. String pathName = name + ".xls";
44. try {
45. pathName = new String(pathName.getBytes(), "ISO-8859-1");
46. } catch (UnsupportedEncodingException e) {
47. e.printStackTrace();
48. }
49. // 获取弹出保存框的保存路径和表名
50. response.setContentType("APPLICATION/OCTET-STREAM");
51. response.setHeader("Content-Disposition", "attachment; filename=\\"" + pathName + "\\"");
52. WritableWorkbook workbook;
53. WorkbookSettings   workbookSettings=new   WorkbookSettings();
54. workbookSettings.setEncoding("GB2312");
55. try {
56. workbook = Workbook.createWorkbook(response.getOutputStream(),workbookSettings);
57. WritableSheet ws = workbook.createSheet("sheet 1", 0);
58. ws.setColumnView(0,22);
59. Label cell = null;
60. for(int i=0;i&lt;2;i++){
61. cell = new Label(0, i+1, "id");
62. ws.addCell(cell);
63. cell = new Label(1, i+1, "name");
64. ws.addCell(cell);
65. }
66. workbook.write();
67. workbook.close();   // 一定要关闭, 否则没有保存Excel;
68. } catch (IOException e) {
69. e.printStackTrace();
70. }catch (WriteException e) {
71. e.printStackTrace();
72. }
73. }
74. }

3、解析过程还是比较简单的。