2017-10-05 120 views
0

我想從表格格式的數據寫入到Excel工作表,在這個日期期間顯示爲「#######」在excel.But而我增加單元格大小的日期是所以我想從代碼本身增加Excel文件的寬度大小。任何人都可以幫助我嗎?代碼如下所示。爪哇鞦韆和Excel

btnExport.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e1) { 

      btnExport.setMnemonic(KeyEvent.VK_X); 

      btnExport.addActionListener(new AksyonListener()); 
     } 

     public void toExcel(JTable table1, File file) { 
      try { 

       System.out.println("Success"); 
       FileWriter excel = new FileWriter(file); 

        // DefaultTableModel model = new DefaultTableModel(); 
       // table.setModel(model); 
        // model.insertRow(table.getRowCount(), new Object[]{0}); 
       for (int i = 0; i < table.getColumnCount(); i++) { 
        excel.write(table.getColumnName(i) + "\t"); 
        System.out.println(table.getColumnName(i)); 
       } 
       /* int d,f; 
       System.out.println("d: "+table.getRowCount()); 
       System.out.println("f: "+table.getColumnCount());*/ 

       excel.write("\n"); 

       for (int i = 1; i < table.getRowCount(); i++) { 

        for (int j = 0; j < table.getColumnCount(); j++) { 

         excel.write(table.getValueAt(i, j) + "\t"); 
         System.out.println(table.getValueAt(i, j)); 
        } 
        excel.write("\n"); 
       } 

       excel.close(); 
      } catch (IOException e) { 
       System.out.println(e); 
      } 
     } 

     class AksyonListener implements ActionListener { 

      public void actionPerformed(ActionEvent e) { 

       if (e.getSource() == btnExport) { 
        JFileChooser fc = new JFileChooser(); 
        int option = fc.showSaveDialog(TableSortFilter.this); 
        if (option == JFileChooser.APPROVE_OPTION) { 
         String filename = fc.getSelectedFile().getName(); 
         String path = fc.getSelectedFile().getParentFile().getPath(); 

         int len = filename.length(); 
         String ext = ""; 
         String file = ""; 

         if (len > 4) { 
          ext = filename.substring(len - 4, len); 
         } 

         if (ext.equals(".xls")) { 
          file = path + "\\" + filename; 
         } else { 
          file = path + "\\" + filename + ".xls"; 
         } 
         toExcel(table, new File(file)); 
        } 
       } 
      } 

     } 

    }); 

回答