[英]Reading Excel Files using c#
我的讀取excel文件的代碼對於許多行均正常工作,但是對於例如(#######)和日期(例如(8/11/2009)),文件中未顯示某些內容,但顯示的日期在其中有一個兩位數的日期,例如(11/12/2011)。
DataTable dtExcel = new DataTable();
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HafizwalaFile + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
string strSQL = "SELECT * FROM [qe$] ";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(strSQL, excelConnection);
dataAdapter.Fill(dtExcel);
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
for (int j = 0; j < dtExcel.Columns.Count;j++ )
{
System.Console.WriteLine(dtExcel.Rows[i][j]);
count_records++;
}
}
在將數據傳輸到表之前,您必須輸入文件excel並調整此列的工作表寬度,如下所示
//using Microsoft.Office.Interop.Excel;
Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
// excelapp.Visible = true;
string filename_Path = @"D:\exmp1.xls";
_Workbook workbook = (_Workbook)(excelapp.Workbooks.Open(filename_Path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelapp .Cells .Columns .AutoFit ();
workbook.Save();
// workbook.Close();
excelapp.Quit();
我建議將excel的該列格式化為日期格式,以使其強制填充0或使其保持純文本。 我認為在C#方面您無能為力
發生這種情況的原因是,您將列的格式設置為Date,並且輸入的數據不是有效日期。 您可以使用以下命令從C#中進行檢查:
MessageBox.Show(dtExcel.Columns[0].DataType.ToString());
Excel將日期和時間存儲為代表自1900年1月0日以來的天數的數字,以及24小時中的一小部分:ddddd.tttttt 閱讀此內容
我嘗試了很多次,發現以下代碼可以正常工作,(請對其進行測試):
String cellValue = "41577.333333"; // 30/10/2013 8:00:00 AM
int days = 0 ;
int hours = 0;
string[] arr = cellValue.Split('.');
days = int.Parse(arr[0]);
if(arr.Length == 2)
{
decimal d_hours = decimal.Parse("0." + arr[1]);
hours =(int) ( d_hours * 24 );
}
TimeSpan dateFromExcel = new TimeSpan(days ,hours ,0,0,0);
DateTime resultingDate = new DateTime(1900,1,1 ,0,0,0).Add(dateFromExcel).AddDays(-2);
MessageBox.Show(resultingDate.ToString());
嘗試使用ACE代替JET,一些網站提到了這一點:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;;Data Source=" + HafizwalaFile + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.