code_junkie

Scientific notation when importing from Excel in .Net

Nov 13th, 2011
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. public void ImportSpreadsheet(string path)
  2. {
  3. string extendedProperties = "Excel 12.0;HDR=YES;IMEX=1";
  4. string connectionString = string.Format(
  5. CultureInfo.CurrentCulture,
  6. "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="{1}"",
  7. path,
  8. extendedProperties);
  9.  
  10. using (OleDbConnection connection = new OleDbConnection(connectionString))
  11. {
  12. using (OleDbCommand command = connection.CreateCommand())
  13. {
  14. command.CommandText = "SELECT * FROM [Worksheet1$]";
  15. connection.Open();
  16.  
  17. using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
  18. using (DataSet columnDataSet = new DataSet())
  19. using (DataSet dataSet = new DataSet())
  20. {
  21. columnDataSet.Locale = CultureInfo.CurrentCulture;
  22. adapter.Fill(columnDataSet);
  23.  
  24. if (columnDataSet.Tables.Count == 1)
  25. {
  26. var worksheet = columnDataSet.Tables[0];
  27.  
  28. // Now that we have a valid worksheet read in, with column names, we can create a
  29. // new DataSet with a table that has preset columns that are all of type string.
  30. // This fixes a problem where the OLEDB provider is trying to guess the data types
  31. // of the cells and strange data appears, such as scientific notation on some cells.
  32. dataSet.Tables.Add("WorksheetData");
  33. DataTable tempTable = dataSet.Tables[0];
  34.  
  35. foreach (DataColumn column in worksheet.Columns)
  36. {
  37. tempTable.Columns.Add(column.ColumnName, typeof(string));
  38. }
  39.  
  40. adapter.Fill(dataSet, "WorksheetData");
  41.  
  42. if (dataSet.Tables.Count == 1)
  43. {
  44. worksheet = dataSet.Tables[0];
  45.  
  46. foreach (var row in worksheet.Rows)
  47. {
  48. // TODO: Consume some data.
  49. }
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56.  
  57. Private Sub Workbook_BeforeClose(Cancel As Boolean)
  58. Application.ErrorCheckingOptions.BackgroundChecking = Ture
  59. End Sub
  60. Private Sub Workbook_Open()
  61. Application.ErrorCheckingOptions.BackgroundChecking = False
  62. End Sub
  63.  
  64. "SELECT Format([F1], 'General Number') From [Sheet1$]"
  65. -or-
  66. "SELECT Format([F1], "#####") From [Sheet1$]"
Add Comment
Please, Sign In to add comment