来自excel的错误数据不正确

时间:2017-01-12 10:51:53

标签: c# excel oledb

我正在使用OLEDB提供程序将数据从excel导入mySql数据库。当有一个包含%的字段时,它会自动除以100.假设我有2列Qty和Disc_Percentage,其值为4和25%。当我从excel表获取数据到datatable时,它将Disc_Percentage值转换为0.25。我有以下代码用于阅读excel

 public static DataTable ConvertExcelFileDataToDataTable(string file, string extension)
            {
                var dtImportedData = new DataTable();

                // -- Start of Constructing OLEDB connection string to Excel file
                var props = new Dictionary<string, string>();

                // For Excel 2007/2010
                if (file.ToLower().EndsWith(".xlsx"))
                {
                    props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
                    props["Extended Properties"] = "\"Excel 12.0\"";
                }
                // For Excel 2003 and older
                else if (file.ToLower().EndsWith(".xls"))
                {
                    props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
                    props["Extended Properties"] = "\"Excel 8.0;IMEX=1;HDR=Yes\"";
                }
                else
                    return null;

                props["Data Source"] = file;

                var sb = new StringBuilder();

                foreach (KeyValuePair<string, string> prop in props)
                {
                    sb.Append(prop.Key);
                    sb.Append('=');
                    sb.Append(prop.Value);
                    sb.Append(';');
                }

                //You must use the $ after the object you reference in the spreadsheet
                var conn = new OleDbConnection(sb.ToString());
                conn.Open();
                var myCommand = new OleDbDataAdapter();
                DataTable dtSerialNumbers = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dtSerialNumbers == null)
                {
                    return dtImportedData;
                }

                var excelSheets = new String[dtSerialNumbers.Rows.Count];

                // Add the sheet name to the string array.
                if (dtSerialNumbers.Rows.Count > 0)
                {
                    //we need the first sheet so save the first sheet name from the first row of the table
                    excelSheets[0] = dtSerialNumbers.Rows[0]["TABLE_NAME"].ToString();
                    myCommand = new OleDbDataAdapter("SELECT * FROM [" + excelSheets[0] + "]", conn);
                }

                myCommand.Fill(dtImportedData);
                dtImportedData.TableName = excelSheets[0].Replace("$", String.Empty);
                return dtImportedData;
            }

1 个答案:

答案 0 :(得分:0)

Excel(2016年在我的机器上)自动检测已输入的&#39;%&#39;并将单元格格式设置为百分比。我建议在导入之前重新格式化这些单元格。