I have to read excel from blob storage(URL is given) and insert some default values in empty cells and upload the excel again in blob without saving it in local anywhere ie insert some dummy values in empty cells. Till now I'm able to traverse the nonempty cells but unable to traverse the empty cells.
//Passing the steam here by using WebClient to read form an URL
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(stream, false))
{
string cellValue;
int columnNumber = -1;
int rowNumber = 0;
WorkbookPart workBookPart = spreadSheetDocument.WorkbookPart;
//selecting the particular sheet
Sheet workSheet = workBookPart.Workbook.Descendants<Sheet>().Where(s =>
s.Name.Value.Equals("Sheet1")).FirstOrDefault();
WorksheetPart workSheetPart = (WorksheetPart)(workBookPart.GetPartById(workSheet.Id));
SheetData sheetData = workSheetPart.Worksheet.Elements<SheetData>().First();
foreach (Row r in sheetData.Elements<Row>())
{
rowNumber++;
columnNumber = -1;
foreach (Cell c in r.Elements<Cell>())
{
string letter;
letter = GetColumnLetter(columnNumber);
while (c.CellReference.ToString().Substring(0, letter.Length) != letter)
{
columnNumber++;
letter = GetColumnLetter(columnNumber);
}
cellValue = GetCellValue(workBookPart, "Sheet1", c.CellReference);
columnNumber++;
}
}
}
}
//Return the cell value
public static string GetCellValue(WorkbookPart workBookPart, string sheetName, string addressName)
{
string value = null;
Sheet mySheet = workBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
if (mySheet == null)
{
throw new ArgumentException("cannot find the following sheet: " + mySheet);
}
WorksheetPart wsPart = (WorksheetPart)(workBookPart.GetPartById(mySheet.Id));
Cell myCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference == addressName).FirstOrDefault();
if (myCell != null)
{
value = myCell.InnerText;
if (myCell.DataType != null)
{
switch (myCell.DataType.Value)
{
case CellValues.SharedString:
var stringTable = workBookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
if (stringTable != null)
{
value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
if (stringTable == null)
{
value = "";
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
case "1":
value = "TRUE";
break;
}
break;
}
}
}
return value;
}
In your function GetCellValue you initialize the return value like
string value = null;
Try to do instead:
string value = string.Empty;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.