gpt4 book ai didi

java excel 到 csv 文件转换

转载 作者:行者123 更新时间:2023-11-29 03:22:15 26 4
gpt4 key购买 nike

我正在尝试将 .xlsx 文件转换为 .csv,转换正在进行但数据格式不正确。请在下面找到代码并对代码提出更改建议。

我在这里尝试读取 .xlsx 文件并将其写入 csv 文件,即将 xlsx 转换为 csv,但我没有以正确的格式获取 .csv 文件所有数据都显示在一个文件中,但它必须显示为Excel 中的行。

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

class XlstoCSV

{

static void xls(File inputFile, File outputFile)

{

// For storing data into CSV files
StringBuffer data = new StringBuffer();
try
{
FileOutputStream fos = new FileOutputStream(outputFile);

// Get the workbook object for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell;
Row row;

// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();

switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + ",");
break;

case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + ",");
break;

case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + ",");
break;

case Cell.CELL_TYPE_BLANK:
data.append("" + ",");
break;

default:
data.append(cell + ",");
}

data.append('\n');
}
}

fos.write(data.toString().getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
File in`enter code here`putFile = new File("C:\test.xls");
File outputFile = new File("C:\output.csv");
xls(inputFile, outputFile);
}
}

最佳答案

尝试将您的代码更改为此你的新行字符必须在一行读取之后附加

while (rowIterator.hasNext()) 
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();

switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + ",");
break;

case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + ",");
break;

case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + ",");
break;

case Cell.CELL_TYPE_BLANK:
data.append("" + ",");
break;

default:
data.append(cell + ",");
}


}
data.append('\n');
}

关于java excel 到 csv 文件转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22958391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com