我正在尝试将xls文件转换为csv。 问题是xls文件(我无法更改)以excel 2工作表版本的形式出现,当您打开它时,您会收到以下消息: “受保护的视图,由于您的策略设置,不允许编辑此文件类型。单击以获取更多详细信息。”
因此,由于出现以下异常,因此无法转换xls文件:
Exception in thread "main" org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0010000200040009, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:151)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:117)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:294)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:400)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:381)
at exceltocsv.ExcelToCSV.main(ExcelToCSV.java:41)
出于测试目的,我删除了保护,因此可以将xls文件保存到新的xls中,并且可以正常工作。但是我不希望用户在运行代码之前操纵文件。
这是我从http://thinktibits.blogspot.com/2012/12/convert-xls-to-csv-in-java-example.html那里获得的代码
try (
FileInputStream input_document = new FileInputStream(new File("C:\\Users\\afusa\\Documents\\NetBeansProjects\\ExcelToCSV\\src\\exceltocsv\\201904TM.xls"))) {
HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
Iterator<Row> rowIterator = my_worksheet.iterator();
FileWriter my_csv = new FileWriter("C:\\Users\\afusa\\Documents\\NetBeansProjects\\ExcelToCSV\\src\\exceltocsv\\convertedCSVFile.csv");
try (CSVWriter my_csv_output = new CSVWriter(my_csv)) {
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
int i = 0;
String[] csvdata = new String[35];
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING || cellType == CellType.BLANK) {
csvdata[i] = cell.getStringCellValue();
} else if (cellType == CellType.NUMERIC) {
csvdata[i] = String.valueOf(cell.getNumericCellValue());
}
i = i + 1;
}
my_csv_output.writeNext(csvdata);
}
}
}
有什么方法可以实现这种转换而无需用户事先操纵excel文件?
答案 0 :(得分:0)
Excel到CSV转换
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
public class ExcelReading {
public static void echoAsCSV(Sheet sheet) throws IOException {
StringBuffer sb=new StringBuffer();
Row row = null;
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
sb.append(row.getCell(j) +",");
}
sb.append("\n");
}
FileOutputStream filout=new FileOutputStream("D:/fileOut.csv");
byte[] strToBytes = sb.toString().getBytes();
filout.write(strToBytes);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
InputStream inp = null;
try {
inp = new FileInputStream("D:\\Book1.xlsx");
Workbook wb = WorkbookFactory.create(inp);
for(int i=0;i<wb.getNumberOfSheets();i++) {
System.out.println(wb.getSheetAt(i).getSheetName());
echoAsCSV(wb.getSheetAt(i));
}
} catch (InvalidFormatException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inp.close();
} catch (IOException ex) {
Logger.getLogger(ExcelReading.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}