How to read and write excel file

后端 未结 22 3185
北荒
北荒 2020-11-22 04:49

I want to read and write an Excel file from Java with 3 columns and N rows, printing one string in each cell. Can anyone give me simple code snippet for this? Do I need to

22条回答
  •  生来不讨喜
    2020-11-22 04:53

    This will write a JTable to a tab separated file that can be easily imported into Excel. This works.

    If you save an Excel worksheet as an XML document you could also build the XML file for EXCEL with code. I have done this with word so you do not have to use third-party packages.

    This could code have the JTable taken out and then just write a tab separated to any text file and then import into Excel. I hope this helps.

    Code:

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    
    public class excel {
        String columnNames[] = { "Column 1", "Column 2", "Column 3" };
    
        // Create some data
        String dataValues[][] =
        {
            { "12", "234", "67" },
            { "-123", "43", "853" },
            { "93", "89.2", "109" },
            { "279", "9033", "3092" }
        };
    
        JTable table;
    
        excel() {
            table = new JTable( dataValues, columnNames );
        }
    
    
        public void toExcel(JTable table, File file){
            try{
                TableModel model = table.getModel();
                FileWriter excel = new FileWriter(file);
    
                for(int i = 0; i < model.getColumnCount(); i++){
                    excel.write(model.getColumnName(i) + "\t");
                }
    
                excel.write("\n");
    
                for(int i=0; i< model.getRowCount(); i++) {
                    for(int j=0; j < model.getColumnCount(); j++) {
                        excel.write(model.getValueAt(i,j).toString()+"\t");
                    }
                    excel.write("\n");
                }
    
                excel.close();
    
            }catch(IOException e){ System.out.println(e); }
        }
    
        public static void main(String[] o) {
            excel cv = new excel();
            cv.toExcel(cv.table,new File("C:\\Users\\itpr13266\\Desktop\\cs.tbv"));
        }
    }
    

提交回复
热议问题