在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java工具类导出jtable数据到excel工作表

2017-2-7 13:41| 发布者: zhangjf| 查看: 498| 评论: 0

摘要: package com.zhong.tools;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import javax.swing.JOptionPane;i ...
  1. package com.zhong.tools;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import javax.swing.JOptionPane;
  8. import javax.swing.JTable;
  9. import javax.swing.table.TableModel;
  10. import jxl.Workbook;
  11. import jxl.write.WritableSheet;
  12. import jxl.write.WritableWorkbook;
  13. import jxl.write.WriteException;
  14. import jxl.write.biff.RowsExceededException;
  15. public class ExcelExporter {
  16. public ExcelExporter() {
  17. }
  18. public void exportTable(JTable table, File file) throws IOException {
  19. try {
  20. OutputStream out = new FileOutputStream(file);
  21. TableModel model = table.getModel();
  22. WritableWorkbook wwb = Workbook.createWorkbook(out);
  23. // 创建字表,并写入数据
  24. WritableSheet ws = wwb.createSheet("中文", 0);
  25. // 添加标题
  26. for (int i = 0; i < model.getColumnCount(); i++) {
  27. jxl.write.Label labelN = new jxl.write.Label(i, 0, model.getColumnName(i));
  28. try {
  29. ws.addCell(labelN);
  30. } catch (RowsExceededException e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. } catch (WriteException e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. }
  37. }
  38. // 添加列
  39. for (int i = 0; i < model.getColumnCount(); i++) {
  40. for (int j = 1; j <= model.getRowCount(); j++) {
  41. jxl.write.Label labelN = new jxl.write.Label(i, j, model.getValueAt(j - 1, i).toString());
  42. try {
  43. ws.addCell(labelN);
  44. } catch (RowsExceededException e) {
  45. e.printStackTrace();
  46. } catch (WriteException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. wwb.write();
  52. try {
  53. wwb.close();
  54. } catch (WriteException e) {
  55. e.printStackTrace();
  56. }
  57. } catch (FileNotFoundException e) {
  58. JOptionPane.showMessageDialog(null, "导入数据前请关闭工作表");
  59. }
  60. }
  61. }
复制代码


来自: http://my.oschina.net/passer007/blog/552515

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 10:16

Copyright 2015-2025 djqfx

返回顶部