简体   繁体   中英

Field splitting in CSV export

I'm exporting my data as a .csv file. I want the first column to be the name and age (separated by a semicolon), with the Address in the second column, both on a single row.

I'm getting the name and age together in one cell, but the address is going on the next row rather than in the second column of the same row.

How should I separate it to get Address to next column?

btnPrint_4 = new JButton("Print");
btnPrint_4.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        //export Excel file
        try{

            new JTextField();
            // create new file
            String path="C:\\ExcelFile.csv";
            File file = new File(path);

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            // write in file                     
            if (txtName.getText() !=null && txtAge.getText() !=null) {
                bw.write(txtName_4.getText());
                bw.write(";");
                bw.write(txtAge.getText());
                //bw.write(System.getProperty("line.separator"));              
                //bw.write("\n");
                bw.write(";");
                bw.write(txtAddress.getText());


            } else {    

                System.out.print("Error :" );
            }                      
            // close connection
            bw.flush();
            bw.close();
            fw.close();
        } catch(Exception e) {
            System.out.println(e);
        }       

Expected Output

在此处输入图片说明

Use tab \\t inplace of ; to separate out the name, age and address column in ouput csv file to display proper columner value in excel

                   bw.write(txtName_4.getText());
                   bw.write("\t");
                   bw.write(txtAge.getText());
                 //bw.write(System.getProperty("line.separator"));             
                 //bw.write("\n");
                   bw.write("\t");
                   bw.write(txtAddress.getText());

I don't understand your problem, your code is working and doing what [I understand at least] you want to do.

bw.write("\n");

creates a new line and

bw.write(System.getProperty("line.separator"));

creates a blank line.

So this code :

for (int i = 1; i < 4; i++) {
        // write in file
        bw.write("Name" + i);
        bw.write(";");
        bw.write("Age" + i);
        bw.write(";");
        bw.write("\n");
        bw.write("Address" + i);
        bw.write(";");
        bw.write(System.getProperty("line.separator"));
        bw.write("\n");
    }

will produce this .csv file :

Name1;Age1;
Address1;

Name2;Age2;
Address2;

Name3;Age3;
Address3;

What did you expect ?

If you want to use semicolons in fields, you just have to surround the field with double-quotes (escaped with a ), it will produce the result expected in your screenshot :

    for (int i = 1; i < 4; i++) {
        // write in file
        bw.write("\"Name" + i);
        bw.write(";");
        bw.write("Age" + i);
        bw.write("\";");
        bw.write("Address" + i);
        bw.write(";");
        bw.write("\n");
    }

Everybody so far is SO close, but not quite. CSV is an acronym for "Comma Separated File". It's become common to use other characters, particularly tabs, to separate columns because real data frequently contains commas, but let's start simple. You need a semicolon between name and age, and a comma between age and address, like so:

if (txtName.getText() !=null && txtAge.getText() !=null) {
    bw.write(txtName_4.getText());
    bw.write(";");
    bw.write(txtAge.getText());
    bw.write(',');
    bw.write(txtAddress.getText());
    bw.write(System.getProperty("line.separator"));              

As long as the text you're writing into the file contains no commas, you'll be fine.

But Erick, what if I have commas in my data?

Never fear, there are several ways around that. The simplest for this application would be to put quotes around the data in each cell, like so:

if (txtName.getText() !=null && txtAge.getText() !=null) {
    bw.write("\"");
    bw.write(txtName_4.getText());
    bw.write(";");
    bw.write(txtAge.getText());
    bw.write("\",\"");
    bw.write(txtAddress.getText());
    bw.write("\"");
    bw.write(System.getProperty("line.separator"));              

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM