我将.xls转换为.csv文件,代码工作正常。但最终输出的最后一个逗号将出现,我不想在我的代码中使用逗号,例如我的输出看起来像ss,dd,ee ,但我不需要最后一个逗号,如何纠正它。
在这里输入代码
import java.io.*;
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;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class convert {
static void convertToXls(File inputFile, File outputFile)
{
// For storing data into CSV files
StringBuffer cellDData = new StringBuffer();
String cellDDataString=null;
try
{
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook instance 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
System.out.println("row"+row);
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();
System.out.println("cell" +cell);
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
cellDData.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
cellDData.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
cellDData.append(cell.getStringCellValue() + ",");
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellDData.append("" + ",");
break;
default:
cellDData.append(cell + ",");
}
}
cellDData.append("\n");
}
//cellDData.append("\n");
//String out=cellDData.toString();
//System.out.println("res"+out);
//String o = out.substring(0, out.lastIndexOf(","));
//System.out.println("final"+o);
fos.write(cellDData.toString().getBytes());
//fos.write(cellDDataString.getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
System.err.println("Exception" + e.getMessage());
}
catch (IOException e)
{
System.err.println("Exception" + e.getMessage());
}
}
public static void main(String[] args)
{
File inputFile = new File("Book1.xls");
File outputFile = new File("output1.csv");
convertToXls(inputFile, outputFile);
}
}
答案 0 :(得分:0)
只需为逗号做一个预构建,并将其添加到追加状态
String szMyComma = "";
while (cellIterator.hasNext())
{
cell = cellIterator.next();
....
cellDData.append(szMyComma + cell.getStringCellValue());
....
szMyComma = ",";
}
答案 1 :(得分:0)
如果cellIterator.hasNext()
为真,则只附加逗号
答案 2 :(得分:0)
试试这个
cellDData.replace(cellDData.length() - 1, cellDData.length(), "");
在行
之前cellDData.append("\n");
答案 3 :(得分:0)
import java.io.*;
import jxl.*;//libary file jxl-2.6.jar need to download
import java.util.*;
class ConvertCSV
{
public static void main(String[] args)
{
try
{
//File to store data in form of CSV
File f = new File("E:\\rajju.csv");
OutputStream os = (OutputStream)new FileOutputStream(f);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw);
//Excel document to be imported
String filename = "D:\\RAJAT\\tds.xls";
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook w = Workbook.getWorkbook(new File(filename),ws);
// Gets the sheets from workbook
for (int sheet = 0; sheet < w.getNumberOfSheets(); sheet++)
{
Sheet s = w.getSheet(sheet);
bw.write(s.getName());
bw.newLine();
Cell[] row = null;
// Gets the cells from sheet
for (int i = 0 ; i < s.getRows() ; i++)
{
row = s.getRow(i);
if (row.length > 0)
{
bw.write(row[0].getContents());
for (int j = 1; j < row.length; j++)
{
bw.write(',');
bw.write(row[j].getContents());
}
}
bw.newLine();
}
}
bw.flush();
bw.close();
}
catch (UnsupportedEncodingException e)
{
System.err.println(e.toString());
}
catch (IOException e)
{
System.err.println(e.toString());
}
catch (Exception e)
{
System.err.println(e.toString());
}
}
}
答案 4 :(得分:0)
在你的第二个while循环中,你总是调用某种形式的cellDData.append(cell +“,”);这是导致逗号总是被添加到最后的原因。
您可以在追加之前执行此操作:
if(cellIterator.hasNext()) {
cellDData.append(value + ",");
} else {
cellDData.append(value);
}
不幸的是,每次在switch语句中调用cellDData.append时都必须进行此检查。更清晰的解决方案可能是将您的值存储为Object,然后在switch语句之后调用cellDData.append。但是,在将值存储为Object之前,应该测试它是否可以按预期的方式工作。
答案 5 :(得分:0)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XlsxtoCSV {
static void xlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
FileInputStream fis = new FileInputStream(inputFile);
Workbook workbook = null;
String ext = FilenameUtils.getExtension(inputFile.toString());
if (ext.equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (ext.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(fis);
}
int numberOfSheets = workbook.getNumberOfSheets();
Row row;
Cell cell;
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
short firstCell = row.getFirstCellNum();
short lastCell = row.getLastCellNum();
String DELIMITER = "";
for(int j = firstCell; j<lastCell; j++){
cell = row.getCell(j);
if(cell==null){
data.append(DELIMITER);
}else {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(DELIMITER + cell.getBooleanCellValue() );
break;
case Cell.CELL_TYPE_NUMERIC:
data.append(DELIMITER + cell.getNumericCellValue() );
break;
case Cell.CELL_TYPE_STRING:
data.append(DELIMITER + cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
data.append(DELIMITER );
break;
default:
data.append(DELIMITER + cell);
}
}
DELIMITER=",";
}
data.append('\n'); //
}
}
fos.write(data.toString().getBytes());
fos.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
}