ITeye博客

应用jxl框架进行Excel文件解析

ssqmeng · 2008-11-05 09:27 · share · J# · Servlet · 框架 · Excel · Markdown

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

2、如下

  1. package test;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import javax.servlet.http.HttpServletResponse;
  6. import jxl.Sheet;
  7. import jxl.Workbook;
  8. import jxl.WorkbookSettings;
  9. 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<row;i++){
  29. for(int j=0;j<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<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、解析过程还是比较简单的。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。