Convert .csv to .xls in Java

后端 未结 6 686
天涯浪人
天涯浪人 2020-12-09 05:48

Does anyone here know of any quick, clean way to convert csv files to xls or xlsx files in java?

I have something to manage csv files already in place and I need the

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 06:11

    Don't know if you know this already, but:

    • Excel (if that's your real target) is easily able to read .csv files directly, so any conversion you'd do would only be a courtesy to your less "gifted" users.
    • CSV is a lowest-common-denominator format. It's unlikely for any converter to add information to that found in a .csv file that will make it more useful. In other words, CSV is a "dumb" format and converting it to .xls will (probably) increase file size but not make the format any smarter.

    Curtis' suggestion of POI is the first thing that would come to my mind too.

    If you're doing this conversion on a Windows machine, another alternative could be Jacob, a Java-COM bridge that would allow you to effectively remote control Excel from a Java program so as to do things like open a file and save in a different format, perhaps even applying some formatting changes or such.

    Finally, I've also had some success doing SQL INSERTs (via JDBC) into an Excel worksheet accessed via the JDBC-ODBC bridge. i.e. ODBC can make an Excel file look like a database. It's not very flexible though, you can't ask the DB to create arbitrarily named .XLS files.


    EDIT:

    It looks to me like readLine() is already not giving you whole lines. How is it to know that carriage return is not a line terminator? You should be able to verify this with debug print statements right after the readLine().

    If this is indeed so, it would suck because the way forward would be for you to

    • either recognize incomplete lines and paste them together after the fact,
    • or write your own substitute for readLine(). A simple approach would be to read character by character, replacing CRs within a CSV string and accumulating text in a StringBuilder until you feel you have a complete line.

    Both alternatives are work you probably weren't looking forward to.

提交回复
热议问题