Date in XLS sheet not parsing correctly

本小妞迷上赌 提交于 2021-01-02 09:15:09

问题


I am trying to read a XLS file using 'XLSX' node-module with a column having dates. After parsing the file what I found is that the dates are of few dates back from that of the dates in the sheet. This is what I a doing.

var workbook = XLSX.readFile(filePath);
var grossPayoutSheet = workbook.Sheets[worksheets[1]];
for (var i in grossPayoutSheet) {
				if (i[0] === "!") continue;
				var col = (!isNaN(parseInt(i.substring(1)))) ? i.substring(0,1) : i.substring(0,2);
				var row = (!isNaN(parseInt(i.substring(1)))) ? parseInt(i.substring(1)) : parseInt(i.substring(2));
				var value = grossPayoutSheet[i].v;
				if (row === 2) {
					var value = grossPayoutSheet[i].v;
					headers[col] = value.trim();
					continue;
				}
				if (row !== 1 && !data[row]) {
					data[row] = {};
				} else if (row !== 1){
					data[row][headers[col]] = value;
				}
			}

the value in the cell B3 is

05/07/2017

but after parsing the value is

B3: { t: 'n', v: 42921, w: '42921' }

I want the date in string format that is I want to change the cell format from 'n' to 's'

Can anyone please me out with this?


回答1:


So I got it working yesterday:

import * as XLSX from 'xlsx'
import * as df from 'dateformat';
// Typescript but easy to convert
const workbook: any = XLSX.read(source, { 'type': type, cellDates: true });
// passing the option 'cellDates': true is important
// ...
// ... until you start reading cells
const cellAddress: any = { c: 5, r: 5 }; // column 5 / row 5 which is a date and formatted like that in xlsx
const cell_ref: string = XLSX.utils.encode_cell(cellAddress);
const cell: any = worksheet[cell_ref];
if (cell) {
    let value: any = cell.v;
    const parsedDate: Date = new Date(value);
    parsedDate.setHours(parsedDate.getHours() + timezoneOffset); // utc-dates
    value = df(parsedDate, "dd/mm/yyyy");
}

This is just a snippet but the essentials are in there :-) Hope this might help you! Btw I am using a xlsx-file.

The trick is to pass the option 'cellDates: true' and then to just instantiate a date from the numbers value and it should work out. Your date will probably be a few hours off because of the utc-dates in JS, which you can even out by adding the offset to the date.




回答2:


var workbook = XLSX.read(data, {
  type: 'binary',
  cellDates: true,
  cellNF: false,
  cellText: false
});



回答3:


 const workbook = excel.readFile(file.path);

 const sheet_name_list = workbook.SheetNames;
 const json = excel.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]], {
  raw: false,
 });


来源:https://stackoverflow.com/questions/44967466/date-in-xls-sheet-not-parsing-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!