java将.xls转换为csv
我已经使用ApachePOI库将.xls文件转换为csv文件。我迭代每一行和每一个单元格,放一个逗号,并附加到缓冲读取器。单元格类型numeric和string的转换非常完美。如果出现空白单元格,我会用逗号,但代码不会检测到空白值。怎么做?请帮帮我java将.xls转换为csv,java,excel,csv,apache-poi,Java,Excel,Csv,Apache Poi,我已经使用ApachePOI库将.xls文件转换为csv文件。我迭代每一行和每一个单元格,放一个逗号,并附加到缓冲读取器。单元格类型numeric和string的转换非常完美。如果出现空白单元格,我会用逗号,但代码不会检测到空白值。怎么做?请帮帮我 import java.io.*; import java.util.Iterator; import java.text.DateFormat; import java.io.IOException; import java.text.Simple
import java.io.*;
import java.util.Iterator;
import java.text.DateFormat;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.math.BigDecimal;
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;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.DateUtil;
class convert {
static void convertToXls(File inputFile, File outputFile)
{
StringBuffer cellDData = new StringBuffer();
String cellDDataString=null;
try
{
FileOutputStream fos = new FileOutputStream(outputFile);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell=null;
Row row;
int previousCell;
int currentCell;
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
previousCell = -1;
currentCell = 0;
row = rowIterator.next();
System.out.println("ROW:-->");
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
// System.out.println("true" +cellIterator.hasNext());
cell = cellIterator.next();
currentCell = cell.getColumnIndex();
System.out.println("CELL:-->" +cell.toString());
try{
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
cellDData.append(cell.getBooleanCellValue() + ",");
System.out.println("boo"+ cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
// System.out.println(cell.getDateCellValue());
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy");
String strCellValue = dateFormat.format(cell.getDateCellValue());
// System.out.println("date:"+strCellValue);
cellDData.append(strCellValue +",");
}
else {
System.out.println(cell.getNumericCellValue());
Double value = cell.getNumericCellValue();
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString());
// System.out.println("number:"+strCellValue1);
cellDData.append(strCellValue1 +",");
}
// cellDData.append(cell.getNumericCellValue() + ",");
//String i=(new java.text.DecimalFormat("0").format( cell.getNumericCellValue()+"," ));
//System.out.println("number"+cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
String out=cell.getRichStringCellValue().getString();
cellDData.append(cell.getRichStringCellValue().getString() + ",");
//System.out.println("string"+cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellDData.append("" + "THIS IS BLANK");
System.out.print("THIS IS BLANK");
break;
default:
break;
}}
catch (NullPointerException e) {
//do something clever with the exception
System.out.println("nullException"+e.getMessage());
}
}
int len=cellDData.length() - 1;
// System.out.println("length:"+len);
// System.out.println("length1:"+cellDData.length());
cellDData.replace(cellDData.length() - 1, cellDData.length() , "");
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) throws IOException
{
File inputFile = new File("/bwdev/kadfeb/xls/Accredo_Kadmon_Monthly_02282014.xls");
File outputFile = new File("output1.csv");
convertToXls(inputFile, outputFile);
}
import java.io.*;
导入java.util.Iterator;
导入java.text.DateFormat;
导入java.io.IOException;
导入java.text.simpleDataFormat;
导入java.util.Date;
导入java.text.DecimalFormat;
导入java.text.NumberFormat;
导入java.math.BigDecimal;
导入org.apache.poi.hssf.usermodel.HSSFSheet;
导入org.apache.poi.hssf.usermodel.HSSFWorkbook;
导入org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.ss.usermodel.Row;
导入org.apache.poi.xssf.usermodel.xssfheet;
导入org.apache.poi.xssf.usermodel.xssf工作簿;
导入org.apache.poi.xssf.usermodel.XSSFRichTextString;
导入org.apache.poi.hssf.usermodel.HSSFDateUtil;
导入org.apache.poi.ss.usermodel.DateUtil;
类转换{
静态void convertoxls(文件输入文件、文件输出文件)
{
StringBuffer cellDData=新的StringBuffer();
字符串cellDDataString=null;
尝试
{
FileOutputStream fos=新的FileOutputStream(outputFile);
HSSFWorkbook=新的HSSFWorkbook(新文件InputStream(inputFile));
HSSFSheet sheet=工作簿。getSheetAt(0);
Cell=null;
行行;
int-previousCell;
int-currentCell;
迭代器rowIterator=sheet.Iterator();
while(roweiterator.hasNext())
{
前一个单元格=-1;
currentCell=0;
行=行迭代器。下一步();
System.out.println(“行:-->”);
迭代器cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
//System.out.println(“true”+cellIterator.hasNext());
cell=cellIterator.next();
currentCell=cell.getColumnIndex();
System.out.println(“CELL:-->”+CELL.toString());
试一试{
开关(cell.getCellType())
{
case Cell.Cell\u类型\u布尔值:
追加(cell.getBooleanCellValue()+“,”);
System.out.println(“boo”+cell.getBooleanCellValue());
打破
case Cell.Cell\u类型\u数值:
if(DateUtil.isCellDateFormatted(单元格))
{
//System.out.println(cell.getDateCellValue());
SimpleDataFormat dateFormat=新SimpleDataFormat(
“年月日”);
String strCellValue=dateFormat.format(cell.getDateCellValue());
//System.out.println(“日期:+strCellValue”);
追加(strCellValue+“,”);
}
否则{
System.out.println(cell.getNumericCellValue());
Double value=cell.getNumericCellValue();
Long longValue=value.longValue();
String strCellValue1=新字符串(longValue.toString());
//System.out.println(“编号:+strCellValue1”);
追加(strCellValue1+“,”);
}
//追加(cell.getNumericCellValue()+“,”);
//字符串i=(新的java.text.DecimalFormat(“0”).format(cell.getNumericCellValue()+“,”));
//System.out.println(“number”+cell.getNumericCellValue());
打破
case Cell.Cell\u类型\u字符串:
String out=cell.getRichStringCellValue().getString();
追加(cell.getRichStringCellValue().getString()+“,”);
//System.out.println(“字符串”+cell.getStringCellValue());
打破
case Cell.Cell\u类型\u空白:
追加(“+”这是空的);
系统输出打印(“此为空白”);
打破
违约:
打破
}}
捕获(NullPointerException e){
//做些聪明的事,但有例外
System.out.println(“nullException”+e.getMessage());
}
}
int len=cellDData.length()-1;
//System.out.println(“长度:+len”);
//System.out.println(“length1:+celldata.length());
celldata.replace(celldata.length()-1,celldata.length(),“”);
cellDData.append(“\n”);
}
//cellDData.append(“\n”);
//String out=cellDData.toString();
//System.out.println(“res”+out);
//字符串o=out.substring(0,out.lastIndexOf(“,”);
//系统输出打印项次(“最终”+o);
fos.write(celldata.toString().getBytes());
//fos.write(celldatastring.getBytes());
fos.close();
}
catch(filenotfounde异常)
{
System.err.println(“异常”+e.getMessage());
}
捕获(IOE异常)
{
System.err.println(“异常”+e.getMessage());
}
}
公共静态void main(字符串[]args)引发IOException
{
File inputFile=新文件(“/bwdev/kadfeb/xls/Accredo_Kadmon_Monthly_02282014.xls”);
File outputFile=新文件(“output1.csv”);
ConvertToXL(输入文件,输出文件);
}
<代码> > p>我假定默认情况下跳过空白单元格或缺少单元格。请尝试设置HSSFWorkBook对象。
可以找到为MissingCellPolicy设置的可能值
使用行索引和列索引代替迭代器
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
HSSFSheet sheet = workbook.getSheetAt(0);
for(int rowIndex = sheet.getFirstRowNum(); rowIndex < sheet.getLastRowNum(); rowIndex++)
{
Cell cell=null;
Row row = null;
previousCell = -1;
currentCell = 0;
row = sheet.getRow(rowIndex);
for(int colIndex=row.getFirstCellNum(); colIndex < row.getLastCellNum(); colIndex++)
{
cell = row.getCell(colIndex);
currentCell = cell.getColumnIndex();
/* Cell processing starts here*/
}
}
HSSFWorkbook工作簿=新的HSSFWorkbook(新文件InputStream(inputFile));
工作簿.setMissingCellPolicy(行.创建为空\u为空);
HSSFSheet sheet=工作簿。getSheetAt(0);
对于(int rowIndex=sheet.getFirstRowNum();rowIndexwhile (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
for (int cn = 0; cn < row.getLastCellNum(); cn++) {
Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);
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);
// Get the workbook object for XLSX file
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);
}
// Get first sheet from the workbook
int numberOfSheets = workbook.getNumberOfSheets();
Row row;
Cell cell;
// Iterate through each rows from first sheet
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(0);
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'); // appending new line after each row
}
}
fos.write(data.toString().getBytes());
fos.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
// testing the application
public static void main(String[] args) {
// int i=0;
// reading file from desktop
File inputFile = new File(".//src//test//resources//yourExcel.xls"); //provide your path
// writing excel data to csv
File outputFile = new File(".//src//test//resources//yourCSV.csv"); //provide your path
xlsx(inputFile, outputFile);
System.out.println("Conversion of " + inputFile + " to flat file: "
+ outputFile + " is completed");
}
}
public class XLSXToCSVConverter {
public InputStream convertxlstoCSV(InputStream inputStream) throws IOException, InvalidFormatException {
Workbook wb = WorkbookFactory.create(inputStream);
return csvConverter(wb.getSheetAt(0));
}
private InputStream csvConverter(Sheet sheet) {
Row row = null;
String str = new String();
for (int i = 0; i < sheet.getLastRowNum()+1; i++) {
row = sheet.getRow(i);
String rowString = new String();
for (int j = 0; j < 3; j++) {
if(row.getCell(j)==null) {
rowString = rowString + Utility.BLANK_SPACE + Utility.COMMA;
}
else {
rowString = rowString + row.getCell(j)+ Utility.COMMA;
}
}
str = str + rowString.substring(0,rowString.length()-1)+ Utility.NEXT_LINE_OPERATOR;
}
System.out.println(str);
return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
}
}