我正在使用Apache POI 3.6,我正在尝试从excel读取数据并将excel数据转换为.CVS文件。 我的Excel数据将采用这种格式
我需要以这种格式(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);
}
答案 0 :(得分:1)
如果Excel将单元格设置为日期/时间,您应该可以通过
获取实际日期Date date = cell.getDateCellValue()
然后,您可以使用SimpleDateFormatter
或类似内容以CSV中的任何方式对其进行格式化。