对于Excel值,不能将types“double”转换为“string”
我正在加载一个Excel文件,正如在网上的许多地方所表明的那样。
OpenFileDialog chooseFile = new OpenFileDialog(); chooseFile.Filter = "Excel files (*.xls,*.xlsl)|*.xls;*.xlsx"; if (chooseFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { selectedFileName = chooseFile.FileName; textBox1.Text = selectedFileName; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(selectedFileName); Sheets excelSheets = wb.Worksheets; string currentSheet = "Sheet 1"; excelWorksheet = (Worksheet)excelSheets.get_Item(currentSheet); Range usedRange = excelWorksheet.UsedRange; Range lastCell = usedRange.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing); lastRow = lastCell.Row; lastColumn = lastCell.Column; //release com object you won't need. Marshal.ReleaseComObject(excel); Marshal.ReleaseComObject(wb); }
当我尝试使用这个函数从单元格中获取单个值时,会出现问题:
private string getCellValue(Worksheet Sheet, int Row, int Column) { var cellValue = (string)(Sheet.Cells[Row, Column] as Range).Value; return cellValue; }
这段代码对许多单元格工作正常,但突然遇到一个引发此exception的单元格:
无法将types“double”转换为“string”
这很奇怪,因为它完全适用于所有其他单元格,并将所有内容转换为string。 这似乎甚至没有给空白单元格带来麻烦。 我也从Excel文件中指定每个单元格为“文本”,但实际上并没有这种行为的线索。
也尝试了这种方式的显式转换。
private string getCellValue(Worksheet Sheet, int Row, int Column) { string cellValue = Sheet.Cells[Row, Column].Value.ToString(); return cellValue; }
现在提出的例外是:
无法对空引用执行运行时绑定
Text属性可用于从单元格中检索文本内容。 所以,你可以尝试使用属性如下:
private string getCellValue(Worksheet Sheet, int Row, int Column) { string cellValue = Sheet.Cells[Row, Column].Text.ToString(); return cellValue; }
尝试这个
private string getCellValue(Worksheet Sheet, int Row, int Column) { object cellValue = Sheet.Cells(Row, Column).Value; if (cellValue != null) { return Convert.ToString(cellValue); } else { return string.Empty; } }
尝试使用下面的代码:
private string getCellValue(Worksheet Sheet, int Row, int Column) { string cellValue = Sheet.Cells[Row, Column].Text.ToString(); return cellValue; }
希望它的作品!
试试:
double dbl =(double)cell.Value; isDouble = String.Format("{0:0}", dbl).ToString();
这对我有用。