开发者

Excel turning my numbers to floats

开发者 https://www.devze.com 2022-12-23 01:53 出处:网络
I have a bit of ASP.NET code that exports data in a datagrid into Excel but I noticed that it messes up a particular field when exporting.

I have a bit of ASP.NET code that exports data in a datagrid into Excel but I noticed that it messes up a particular field when exporting.

E.g. I have the value of something like 89234010000725515开发者_C百科875 in a column in the datagrid but when exported, it turns it into 89234+19.

Is there any Excel formatting that will bring back my original number? Thanks.


Excel isn't really messing up the field. Two things are happening:

  1. Excel formats large numbers in scientific notation. So "89234010000725515875" becomes "8.9234E+19" or "8.9234 x 10 ^ 19".
  2. The size of the number "89234010000725515875" exceeds the precision in which Excel uses to store values. Excel stores your number as "89234010000725500000" so you're losing the last five digits.

Depending on your needs you can do one of two things.

Your first option is to change the formatting from "General" to "0" (Number with zero decimal places.) This will give you "89234010000725500000" so you will have lost precision but you will be able to perform calculcations on the number.

The second option is to format the cell as text "@" or to paste your field with an apostrophe at the beginning of the line to force the value to be text. You'll get all of the digits but you won't be able to do calculations of the value.

I hope this helps.


You can add a space to the field, then when you export it to Excel, it's considered as string:

lblTest.Text = DTInfo.Rows(0).Item("Test") & " "

Good luck.


Below is the C# source code to do this with SpreadsheetGear for .NET. Since the SpreadsheetGear API is similar to Excel's API, you should be able to easily adapt this code to Excel's API to get the same result.

You can download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

using System;
using SpreadsheetGear;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new workbook and get a reference to A1.
            IWorkbook workbook = Factory.GetWorkbook();
            IWorksheet worksheet = workbook.Worksheets[0];
            IRange a1 = worksheet.Cells["A1"];
            // Format A1 as Text using the "@" format so that the text
            // will not be converted to a number, and put the text in A1.
            a1.NumberFormat = "@";
            a1.Value = "89234010000725515875";
            // Show that the formatted value is 
            Console.WriteLine("FormattedValue={0}, Raw Value={1}", a1.Text, a1.Value);
            // Save the workbook.
            workbook.SaveAs(@"c:\tmp\Text.xls", FileFormat.Excel8);
            workbook.SaveAs(@"c:\tmp\Text.xlsx", FileFormat.OpenXMLWorkbook);
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号