【发布时间】:2019-04-29 20:01:36
【问题描述】:
我正在将 CSV 文件转换为 XLS 文件。 当我进行转换时,一切正常;但是,当单元格内有逗号时,它将一列分成两列。
前: |你好世界! | CSV 文件 |
转换后
|你好 |世界! | CSV 文件 | X --- 我目前得到的
|你好世界! | CSV 文件 | O --- 我想要什么
字符串 ab = thisLine.replaceAll(", ", " ");
假设每个人都在使用逗号后使用空格,replaceAll 会起作用,但这不是一个理想的解决方案。
public void csv2excel(String csv) throws Exception
{
String inputCSVFile = csv + ".csv";
ArrayList arList=null;
ArrayList al=null;
String fName = inputCSVFile;
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 ab = thisLine.replaceAll(", ", " ");
//String strar[] ab.split(",");
String strar[] = thisLine.split(",");
//Here is where I split the columns.
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
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(CellType.STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(CellType.STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(csv + ".xls");
hwb.write(fileOut);
fileOut.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
myInput.close();
fis.close();
}
我想知道是否有一种方法可以逐列拆分。
【问题讨论】: