i'm using open xml sdk dll in my Asp net MVC for uploading excel into my website.
there is 4 column in my excel file Name , Email , Company Name and Phone Number.
i use following code to get excel file from my view and save it in local disk and then access to it's cell for saving in my database.
**but there is problem in debugging the code. when i want to access cell that contain string it shows me it contains 0 but there is no problem in reading numbers.
it shows zero when my foreach item goes on cells that contains string .** any idea's?
edited Question: i managed to read cell's value with this code modification but there is another problem.according to This answer i should read shared string to read string but when i read DataType , it valued null in some random moment. so i cant read some cell's. i cant find the problem
here is controller code:
[HttpPost]
public IHttpActionResult UploadExcelFile()
{
try
{
var rnd = new Random();
string filePath = "";
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count < 1)
{
return Content(HttpStatusCode.BadRequest, "there's no file selected");
}
var guid = rnd.Next(999);
var postedFile = httpRequest.Files[0];
var serverFilePath = HttpContext.Current.Server.MapPath("~/Content/Email/" + guid + Path.GetExtension(postedFile.FileName));
filePath = "/Content/Email/" + guid + Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(serverFilePath);
using (SpreadsheetDocument spreadsheetDocument =SpreadsheetDocument.Open(serverFilePath, false))
{
List<string> colName = new List<string>(new string[] { "A", "B", "C","D" });
var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>();
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
Worksheet worksheet = worksheetPart.Worksheet;
var rowCount = GetRowCount(worksheet);
for (int i = 0; i < rowCount; i++)
{
Cell cell = GetCell(worksheet, colName[i], i+1);
Row row = GetRow(worksheet, i+1);
foreach (var item in row.ChildElements)
{
List<string> cellValue = new List<string>();
if (cell.DataType != null)
{
if (cell.DataType == CellValues.SharedString)
{
int id = -1;
if (Int32.TryParse(cell.InnerText, out id))
{
SharedStringItem x = GetSharedStringItemById(workbookPart, id);
if (x.Text != null)
{
cellValue.Add(x.Text.Text);
}
else if (item.InnerText != null)
{
cellValue.Add(x.InnerText);
}
else if (item.InnerXml != null)
{
cellValue.Add(x.InnerXml);
}
}
}
}
else
{
cellValue.Add(item.InnerText);
}
}
}
}
return Ok(new { message = "Record has been saved successfully" });
}
catch (Exception e)
{
return Content(HttpStatusCode.BadRequest, "there's problem with Server");
throw;
}
}