在Java中将.csv转换为.xls

Jus*_*yer 10 java csv xls xlsx

有没有人知道在java中将csv文件转换为xls或xlsx文件的任何快速,干净的方法?

我有一些东西来管理已经存在的csv文件,我需要其他程序的额外兼容性.

除包名之外的示例代码总是很受欢迎.

非常感谢,

瑞斯蒂昂

到目前为止,这是我的代码.我需要从行中删除返回("\n").我的一些单元格包含多行信息(列表),因此我可以在csv中使用"\n"来表示单元格中的多行,但xls将这些视为将其置于新行中.

代码是从互联网上修改的,目前有点乱.您可能会注意到一些已弃用的方法,因为它是在2004年编写的,并且一定要忽略可怕的返回语句.我现在正在使用Sop进行测试,之后我会把它清理干净.

package jab.jm.io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class FileConverter {

    public static String ConvertCSVToXLS(String file) throws IOException {

        if (file.indexOf(".csv") < 0)
            return "Error converting file: .csv file not given.";

        String name = FileManager.getFileNameFromPath(file, false);
        ArrayList<ArrayList<String>> arList = new ArrayList<ArrayList<String>>();
        ArrayList<String> al = null;

        String thisLine;
        DataInputStream myInput = new DataInputStream(new FileInputStream(file));

        while ((thisLine = myInput.readLine()) != null) {
            al = new ArrayList<String>();
            String strar[] = thisLine.split(",");

            for (int j = 0; j < strar.length; j++) {
                // My Attempt (BELOW)
                String edit = strar[j].replace('\n', ' ');
                al.add(edit);
            }

            arList.add(al);
            System.out.println();
        }

        try {
            HSSFWorkbook hwb = new HSSFWorkbook();
            HSSFSheet sheet = hwb.createSheet("new sheet");

            for (int k = 0; k < arList.size(); k++) {
                ArrayList<String> ardata = (ArrayList<String>) arList.get(k);
                HSSFRow row = sheet.createRow((short) 0 + k);

                for (int p = 0; p < ardata.size(); p++) {
                    System.out.print(ardata.get(p));
                    HSSFCell cell = row.createCell((short) p);
                    cell.setCellValue(ardata.get(p).toString());
                }
            }

            FileOutputStream fileOut = new FileOutputStream(
                    FileManager.getCleanPath() + "/converted files/" + name
                            + ".xls");
            hwb.write(fileOut);
            fileOut.close();

            System.out.println(name + ".xls has been generated");
        } catch (Exception ex) {
        }

        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

Car*_*icz 7

不知道你是否已经知道这一点,但是:

  • Excel(如果这是你真正的目标)很容易.csv直接读取文件,所以你所做的任何转换只会对你那不那么"有天赋"的用户有礼貌.
  • CSV是最低公分母格式.任何转换器都不太可能将信息添加到.csv文件中找到的信息,这将使其更有用.换句话说,CSV是一种"哑"格式,并将其转换为.xls将(可能)增加文件大小但不会使格式更智能.

柯蒂斯对POI的建议也是我想到的第一件事.

如果你在Windows机器上进行这种转换,另一个替代方案可能是Jacob,一个Java-COM桥,它允许你从Java程序中有效地远程控制Excel,以便做一些事情,比如打开一个文件并保存在另一个格式,甚至可能应用一些格式更改等.

最后,我还INSERT通过JDBC-ODBC桥访问Excel工作表(通过JDBC)取得了一些成功.即ODBC可以使Excel文件看起来像数据库.但它不是很灵活,你不能要求DB创建任意命名的.XLS文件.


编辑:

它看起来像是readLine()已经没有给你全线了.怎么知道回车不是线路终结者?您应该能够在readLine()之后使用debug print语句验证这一点.

如果确实如此,它会很糟糕,因为前进的方向对你而言

  • 要么识别不完整的线条,要么将它们粘贴在一起,
  • 或编写自己的readLine()替代品.一种简单的方法是逐个字符地读取,替换CSV字符串中的CR并在StringBuilder中累积文本,直到您感觉有完整的行.

两种选择都是你可能不期待的工作.


use*_*934 6

复制粘贴下面的程序,我运行了程序,它运行正常,如果您对此程序有任何疑问,请告诉我。(您需要Apache POI Jar才能运行此程序)

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;


public class CSVToExcelConverter {

    public static void main(String args[]) throws IOException
    {
        ArrayList arList=null;
        ArrayList al=null;
        String fName = "test.csv";
        String thisLine;
        int count=0;
        FileInputStream fis = new FileInputStream(fName);
        DataInputStream myInput = new DataInputStream(fis);
        int i=0;
        arList = new ArrayList();
        while ((thisLine = myInput.readLine()) != null)
        {
            al = new ArrayList();
            String strar[] = thisLine.split(",");
            for(int j=0;j<strar.length;j++)
            {
                al.add(strar[j]);
            }
            arList.add(al);
            System.out.println();
            i++;
        }

        try
        {
            HSSFWorkbook hwb = new HSSFWorkbook();
            HSSFSheet sheet = hwb.createSheet("new sheet");
            for(int k=0;k<arList.size();k++)
            {
                ArrayList ardata = (ArrayList)arList.get(k);
                HSSFRow row = sheet.createRow((short) 0+k);
                for(int p=0;p<ardata.size();p++)
                {
                    HSSFCell cell = row.createCell((short) p);
                    String data = ardata.get(p).toString();
                    if(data.startsWith("=")){
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        data=data.replaceAll("\"", "");
                        data=data.replaceAll("=", "");
                        cell.setCellValue(data);
                    }else if(data.startsWith("\"")){
                        data=data.replaceAll("\"", "");
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(data);
                    }else{
                        data=data.replaceAll("\"", "");
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(data);
                    }
                    //*/
                    // cell.setCellValue(ardata.get(p).toString());
                }
                System.out.println();
            }
            FileOutputStream fileOut = new FileOutputStream("test.xls");
            hwb.write(fileOut);
            fileOut.close();
            System.out.println("Your excel file has been generated");
        } catch ( Exception ex ) {
            ex.printStackTrace();
        } //main method ends
    }
}
Run Code Online (Sandbox Code Playgroud)


Cur*_*tis 5

如果您想用Java读取或写入XLS或XLSX文件,Apache POI是一个不错的选择:http://poi.apache.org/