[英]How to get the exact value saved in Excel sheet using C#?
我在Excel工作表的單元格中輸入DateTime.Now.ToUniversalTime().ToLongTimeString()
並在保存后將其關閉,但是在再次打開同一Excel工作表並嘗試獲取其單元格值時, DateTime.Now.ToUniversalTime().ToLongTimeString()
了我一些雙重價值。
我的C#代碼:
在構造函數中:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet, xlWorkSheet2, xlWorkSheet3;
object misValue = System.Reflection.Missing.Value;
Excel.Range range;
xlWorkBook = xlApp.Workbooks.Open(
"Book1.xls",
0,
true,
misValue,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
((Excel.Range)xlWorkSheet.Cells[1, 5]).EntireColumn.NumberFormat = "H:mm:ss";
xlWorkSheet.Cells[(rowcnt + 1), 5] = DateTime.Now.ToUniversalTime().ToLongTimeString();
xlWorkBook.SaveAs("Book2.xls",Excel.XlFileFormat.xlOpenXMLWorkbook);
//Close the Excel Workbook after saving a copy of it.
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
xlWorkBook = null;
//Make the Excel Application null.
xlApp = null;
然后調用以下方法獲取單元格值。
private void AddXMLDetail()
{
try
{
xlApp = new Excel.ApplicationClass();
#region Open the Excel File
//Assigning the saved changes workbook present in
//"My Document" to add the xml detail in excel sheet.
xlWorkBook =
xlApp.Workbooks.Open(
"Book2.xls",
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);
#endregion Open the Excel File.
//Assigning Sheet 1.
xlWorkSheet =
(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
string compareTime =
((Excel.Range)range.Cells[1, 5]).Value2.ToString();
Console.WriteLine("The saved cell value is : " + compareTime);
#region Close and Release the object.
//Close the Excel Workbook after saving a copy of it.
xlWorkBook.Close(true, misValue, misValue);
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
xlWorkBook = null;
//Quit The Excel Application after success completion of work.
xlApp.Quit();
//Release the Excel Application for reuse.
Marshal.ReleaseComObject(xlApp);
//Make the Excel Application null.
xlApp = null;
#endregion Close and Release the object.
}
catch (Exception ex)
{
Console.WriteLine("exception was : " + ex);
}
}
誰能告訴我我在哪里做錯了嗎?任何答案都將不勝感激。
使單元格numberFormat為Text
((Excel.Range)xlWorkSheet.Cells[1,5]).EntireColumn.NumberFormat = "@";
然后嘗試像現在一樣將相同的值獲取到字符串變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.