我正在使用 Apache POI 3.6,我正在尝试从 Excel 读取数据并将 Excel 数据转换为 .CVS 文件。 我的 Excel 数据将采用这种格式
- 第一列为:日期(8/6/2009)
- 第二列将为:时间(12:00:01 AM)
- 第三列将为:值 1 (30)
- 第四列将为:值 2 (400.99)。
我需要将此数据转换为这种格式 (8-6-2009) 并将其存储在 CVS 文件中 错误:我可以将数据存储在 csv 文件中,但无法转换其中的日期和时间。它采用一些值 在日期列中我得到 41426,在时间列中我得到 3456.0。
我不知道如何转换上面的内容: 请任何人帮助我..:(
我的代码在这里:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel {
static void xlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
FileInputStream fio = new FileInputStream(inputFile);
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(fio);
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;
// 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:
if (row.getCell(0).getCellType() == Cell.CELL_TYPE_NUMERIC){
data.append(cell.getNumericCellValue() + ",");
}
if (DateUtil.isCellDateFormatted(row.getCell(0))) {
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getDateCellValue());
data.append(row.getCell(0).getDateCellValue() + ",");
}
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("\r\n");
}//System.out.println();
//System.out.println(data);
fos.write(data.toString().getBytes());
fos.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
}
//testing the application
public static void main(String[] args) {
//reading file from desktop
File inputFile = new File("D:\\project-work\\sampleData.xlsx");
//writing excel data to csv
File outputFile = new File("D:\\project-work\\Data.csv");
xlsx(inputFile, outputFile);
}
最佳答案
如果 Excel 将单元格正确设置为日期/时间,您应该能够通过以下方式获取实际日期
Date date = cell.getDateCellValue()
然后您可以使用 SimpleDateFormatter
或类似工具在 CSV 中按照您需要的任何方式对其进行格式化。
关于java - 将 Excel 转换为 .csv 文件时,我无法转换日期并将其保存在 csv 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076767/