本文介绍了我们如何在阅读excelsheet时忽略空单元格值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在读取excel文件时,空单元格值生成错误...我想忽略空单元格值..
我尝试了什么:
while reading excel file, empty cell value generate the error...I want to ignore the empty cell value..
What I have tried:
public static DataTable GetDataTableFromSpreadsheet(Stream MyExcelStream, bool ReadOnly)
{
DataTable dt = new DataTable();
using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(MyExcelStream, ReadOnly))
{
WorkbookPart workbookPart = sDoc.WorkbookPart;
IEnumerable<Sheet> sheets = sDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)sDoc.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
SheetData sheetData = workSheet.GetFirstChild<SheetData>();
IEnumerable<Row> rows = sheetData.Descendants<Row>();
foreach (Cell cell in rows.ElementAt(0))
{
dt.Columns.Add(GetCellValue(sDoc, cell));
}
foreach (Row row in rows) //this will also include your header row...
{
DataRow tempRow = dt.NewRow();
for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
{
if (tempRow[i] == DBNull.Value || String.IsNullOrWhiteSpace(tempRow[i].ToString()))
{
continue;
}
else
{
tempRow[i] = GetCellValue(sDoc, row.Descendants<Cell>().ElementAt(i));
}
}
dt.Rows.Add(tempRow);
}
}
dt.Rows.RemoveAt(0);
return dt;
}
推荐答案
if (tempRow[i] == DBNull.Value || String.IsNullOrWhiteSpace(tempRow[i].ToString()))
到
if (DBNull.Value.Equals(tempRow[i]) || String.IsNullOrWhiteSpace(tempRow[i].ToString()))
这篇关于我们如何在阅读excelsheet时忽略空单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!