简体   繁体   English

C# ExcelWorksheet 单元格值读取错误

[英]C# ExcelWorksheet cell value is read incorrectly

I am parsing a csv file using C# and ExcelWorksheet.我正在使用 C# 和 ExcelWorksheet 解析 csv 文件。 I have a cell that contains an integer.我有一个包含 integer 的单元格。 3020191002155959391100

When I parse the cell using当我使用解析单元格时

var value = sheet.Cells[rowNumber, columnNumber.Column].Value; value is 3.0201910021559592E+21值为3.0201910021559592E+21

when I parse the cell using sheet.Cells[rowNumber, columnNumber.Column].Text;当我使用 sheet.Cells[rowNumber, columnNumber.Column].Text; 解析单元格时the value is 3020191002155960000000值为3020191002155960000000

how do I prevent the rounding off?如何防止四舍五入?

The maximum value of an int in C# is C#中一个int的最大值是

int.MaxValue: 2,147,483,647 int.MaxValue: 2,147,483,647

Source: https://www.dotnetperls.com/int-maxvalue资料来源: https://www.dotnetperls.com/int-maxvalue

Therefore your number is too big to be read as an int .因此,您的数字太大而无法读取为int

However, upon reading your comments it appears that you're using the Excel reader to read a CSV file, which is the wrong tool for the job.但是,在阅读您的评论后,您似乎正在使用 Excel 阅读器来阅读CSV文件,这是该工作的错误工具。 Use a CSV parser such as CSVHelper ( https://joshclose.github.io/CsvHelper/ ) which will make your life easy.使用CSV解析器,例如CSVHelper ( https://joshclose.github.io/CsvHelper/ ),这将使您的生活变得轻松

Here's an example of how to read such long numbers as string using CSVHelper .这是一个如何使用CSVHelper读取字符串等长数字的示例。

First I'll create a class to match your CSV file.首先,我将创建一个 class 以匹配您的 CSV 文件。 I created a dummy CSV file that looks like the following.我创建了一个虚拟 CSV 文件,如下所示。 Simply, three long numbers in a row.简单地说,连续三个长数字。

3020191002155959391100,3020191002155959391101,3020191002155959391102 3020191002155959391100,3020191002155959391101,3020191002155959391102

Now I create a class like so:现在我像这样创建一个 class :

class CSVRecord
{
    public string Data1 { get; set; }
    public string Data2 { get; set; }
    public string Data3 { get; set; }
}

Then you can read all the records in one go.然后您可以读取一个 go 中的所有记录。 Note the csv.Configuration settings, depending on the complexity of the file you read you'll have to change those.请注意csv.Configuration设置,根据您阅读的文件的复杂性,您必须更改这些设置。 I advice you to read the documentation and examples on the link provided.我建议您阅读所提供链接上的文档和示例。

var file = @"data.csv";
var records = new List<CSVRecord>();

using (var reader = new StreamReader(file))
{
    using (var csv = new CsvReader(reader))
    {
        csv.Configuration.HasHeaderRecord = false;
        records = csv.GetRecords<CSVRecord>().ToList();
    }
}

I needed to set the specific column types to string, before processing each cell.在处理每个单元格之前,我需要将特定的列类型设置为字符串。

columnDataTypes.Add(eDataTypes.String);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM