简体   繁体   中英

Exporting from C# to Excel with numbers that use a comma as a decimal point?

I want to export numerical data from C# to Excel where the floating point numbers use a comma (',') for the decimal instead of the dot ('.'). I am exporting Excel file by writing XML code in C#.

The data is properly exported from the code side, but the Excel file omits the (',') if the type of data is "number". When I generate the same data for the English language, it generates perfectly.

Example: number = 65,4 then in Excel file it shows 654.

sample code : --xml code

 <?xml version="1.0" encoding="UTF-8" ?>
<?mso-application progid="Excel.Sheet"?>
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:html="http://www.w3.org/tr/rec-html40">
<ss:Worksheet ss:Name="test">
<ss:Table>
<ss:Row>
<ss:Cell ss:StyleID="s65"><ss:Data ss:Type="String">123</ss:Data></ss:Cell>
<ss:Cell ss:StyleID="s65"><ss:Data ss:Type="Number">64,3</ss:Data></ss:Cell>
<ss:Cell ss:StyleID="s65"><ss:Data ss:Type="Number">72,0</ss:Data></ss:Cell>
<ss:Cell ss:StyleID="s65"><ss:Data ss:Type="Number">26,0</ss:Data></ss:Cell>
<ss:Cell ss:StyleID="s65"><ss:Data ss:Type="Number">72,0</ss:Data></ss:Cell></ss:Row>
</ss:Table>
</ss:Worksheet></ss:Workbook>

c# code --

    Dim excelXml As String = GetExcelXml(dsInput, filename)
    Response.Clear()
    Response.AppendHeader("Cache-Control", "cache, must-revalidate")
    Response.AppendHeader("Pragma", "public")
    Response.AppendHeader("Content-Type", "application/vnd.ms-excel")
    ' Response.ContentEncoding = System.Text.Encoding.GetEncoding(1252)
    Response.Charset = "iso-8859-1"
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.AppendHeader("Content-disposition", "attachment; filename=" &   
         System.IO.Path.GetFileName(filename))
    Response.Write(excelXml)
    Response.Flush()
    Response.[End]()

In your code after you call GetExcelXml to read in your XML file to a string, go through the string and convert all the numbers so that the commas are periods. You should be able to do it with one line of code using Regular Expressions.

For example, below is a line of code that will convert all the XML Number types to use the dot instead of the comma. After it's converted write out the excelXMLCorrected to your Excel file. This function will work regardless of what language your generate your XML in:

excelXMLCorrected = Regex.Replace(excelXml, 
   @"<ss:Data ss:Type=""Number"">([\d]+),([\d]{1})</ss:Data>", 
   "<ss:Data ss:Type=\"Number\">$1.$2</ss:Data>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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