简体   繁体   中英

Super CSV (Java) - Read Files with Spaces in Column Names

I'm working with Super CSV and it looks like an amazing package.

My only worry is how to work with columns with spaces in their names. No, I cannot go back and remove the spaces myself. These files will be given to me by the hundreds and I don't have time to go back and fix all 60 columns for each file and I can't trust everyone else to do it properly.

How can I work with columns with spaces in the title (ie "First Name" not "FirstName" or "firstName")?

Thanks!

For coding samples, look here: http://supercsv.sourceforge.net/codeExamples_general.html

You notice this line in the samples you link to:

final String[] header = inFile.getCSVHeader(true);

This should give you your column names, no?

http://supercsv.sourceforge.net/javadoc/index.html

I think I understand your question now. The String[] argument passed to the read function takes the property names of the class you want to read into. It is positional, so it doesn't have to be named anything like the headers. So, for example, you can have String[] header = inFile.getCSVHeader() , but then have a mapping of headerName->propertyName , so, if your header fields were:

First Name, Last Name, Age

but your class was

getFirstName(), setFirstName(...);
getLastName(), setLastName(...);
getYears(), setYears();

pass to the read method not (String[]) {"First Name", "Last Name", "Age"} , as your header is, but pass to read , a (String[]) {"FirstName", "LastName", "Years"} array.

如果要使用不同的名称映射CSV标头,可以创建一个哈希映射并将其用于内部实现,例如,您可以将“First Name”映射到“firstName”,并根据您的内部名称填充您的bean。

要有一个带空格的标题分隔bean映射和标题数组。

private final String[] header = new String[] { "First Name", "Last Name"}; private final String[] dataMapping = new String[] { "firstName", "lastName"}; beanWriter = new CsvBeanWriter(new FileWriter(path), CsvPreference.EXCEL_PREFERENCE); beanWriter.writeHeader(header); beanWriter.write(yourPojo, dataMapping, processors);

I realize this is quite an old post but others may be looking for an alternative simple solution. This is what I did to ensure I had only alph numeric header names with no spaces:

  final String[] header = beanReader.getHeader(true);

  for(int i = 0; i <= header.length -1 ; i++ ) {
    header[i] = header[i].replaceAll("[^a-zA-Z0-9]+","");
  }

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