Open XML generates only <NewDataSet /> tag from a full Excel file, but work for other files - asp.net

I have an excel file full of data, and I'm trying to use Open XML SDK to convert this file into xml file.
I followed the documentation and other questions here on stackoverflow. However, the output of the xml file is always <NewDataSet />. Knowing that I tried other excel files and it worked fine.
Here is how my excel file looks like:
And here is my code "I tried two approaches":
The first approach is to use DataSet.GetXML(), it returned the same value as the next code does.
var xmlDS = new ConvertExcelToXml().GetXML(filePath);
string xmlPath = server.MapPath("~/UploadedFiles/XML/");
StreamWriter xmlFile = new StreamWriter(xmlPath + Path.GetFileNameWithoutExtension(fileName) + ".xml");
xmlDS.WriteXml(xmlFile);
//The used method to return the excel file dataset
public DataSet GetXML(string filename)
{
using (DataSet ds = new DataSet())
{
ds.Tables.Add(this.ReadExcelFile(filename));
return ds;
}
}
//This method used to return DataTable for previous method
private DataTable ReadExcelFile(string filename)
{
DataTable dt = new DataTable();
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheetcollection.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId);
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rowcollection = sheetData.Descendants<Row>();
if (rowcollection.Count() == 0)
{
return dt;
}
foreach (Cell cell in rowcollection.ElementAt(0))
{
dt.Columns.Add(GetValueOfCell(spreadsheetDocument, cell));
}
foreach (Row row in rowcollection)
{
DataRow temprow = dt.NewRow();
int columnIndex = 0;
foreach (Cell cell in row.Descendants<Cell>())
{
int cellColumnIndex = GetColumnIndex(GetColumnName(cell.CellReference));
if (columnIndex < cellColumnIndex)
{
do
{
temprow[columnIndex] = string.Empty;
columnIndex++;
}
while (columnIndex < cellColumnIndex);
}
temprow[columnIndex] = GetValueOfCell(spreadsheetDocument, cell);
columnIndex++;
}
dt.Rows.Add(temprow);
}
}
dt.Rows.RemoveAt(0);
return dt;
}
catch (IOException ex)
{
throw new IOException(ex.Message);
}
}

Related

How to use Tempdata to display the list

I have did the excel upload in dotnet core .I had to use tempdata to retrieve the details of the excel in list.Instead in my below code i had used Static object to retrieve the list.My code works as like this ,when i click on upload button it will display the details in the excel sheet.and when click on save it will save it to database and i need to edit in grid view using ajax call also .Help me out
My Action in controller is
public async Task<IActionResult> ImportEmployeeDetails(IFormFile excelfile)
{
try
{
EmployeesViewModelList employeesListObject = new EmployeesViewModelList();
List<EmployeeModel> employeesViewModelList = new List<EmployeeModel>();
if (excelfile == null || excelfile.Length == 0)
{
return View(employeesListObject);
}
var supportedTypes = new[] { ".xls", ".xlsx" };
var ext = Path.GetExtension(excelfile.FileName);
if (!supportedTypes.Contains(ext))
{
return View(employeesListObject);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot",
"EmployeeDetails.xlsx");
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
using (var stream = new FileStream(path, FileMode.Create))
{
await excelfile.CopyToAsync(stream);
}
FileInfo file = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
for (int i = 2; i <= rowCount; i++)
{
EmployeeModel emp = new EmployeeModel();
emp.EmployeeId = Convert.ToInt32(worksheet.Cells[i, 1].Value.ToString());
emp.EmpFirstName = worksheet.Cells[i, 2].Value.ToString();
employeesViewModelList.Add(emp);
}
employeesListObject.EmpModelList = employeesViewModelList;
return View(employeesListObject);
}
}
catch(Exception ex)
{
TempData["Message"] = "Opps! Something Went wrong!";
return RedirectToAction("ExcelPackage");
}
}
Try this, using your own list.
List<string> SomeList = new List<string>();
TempData["MyList"] = SomeList;
//then to get data just do
SomeList = TempData["MyList"] as List<string>; //This converts back to List<T>
Once you add the list to the TempData, you can retrive it from any Action or View in the same controller

Export to CSV not working in mobile handheld device using c#

I am working with Mobile Handheld device application using c#, trying to export datatable to csv file but none of method are working for me,
Plateform Visual Studio 2008 and Smart Device Application.
File.WriteALLText method is not working in smart device application.
private void btnsubmit_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter("logs.txt");
try
{
if (!string.IsNullOrEmpty(txtOutput.Text) && !string.IsNullOrEmpty(txtqty.Text))
{
DataTable dt;
dt = new DataTable();
dt.Columns.Add("Barcode", System.Type.GetType("System.String"));
dt.Columns.Add("Location", System.Type.GetType("System.String"));
dt.Columns.Add("Quantity", System.Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Barcode"] = txtOutput.Text.Trim();
dr["Location"] = "123";
dr["Quantity"] = txtqty.Text.Trim();
dt.Rows.Add(dr);
StringBuilder data = ConvertDataTableToCsvFile(dt);
SaveData(data, #"Data.csv");
MessageBox.Show("Data exported Success");
}
else
{
MessageBox.Show("Please enter all value");
}
txt.Close();
}
catch (Exception ex)
{
string errmsg = ex.Message.ToString();
MessageBox.Show("error " + errmsg);
}
txt.Close();
}
public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)
{
StringBuilder data = new StringBuilder();
for (int column = 0; column < dtData.Columns.Count; column++)
{
//Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";"));
else
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";") + ',');
}
data.Append(Environment.NewLine);//New line after appending columns.
for (int row = 0; row < dtData.Rows.Count; row++)
{
for (int column = 0; column < dtData.Columns.Count; column++)
{
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";"));
else
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";") + ',');
}
if (row != dtData.Rows.Count - 1)
data.Append(Environment.NewLine);
}
return data;
}
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
}
}
I've had same issue, years ago when starting with Handheld device with Windows mobile on them. You should add objWriter.Flush() in SaveData:
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
objWriter.Flush();
}
}

Adding Fields to DataTable in ASP.net MVC

Users are uploading an Excel file to my site which I'm then going to write to the database. I'd like to add two additional columns (Email and TimeStamp). I'm not getting any specific error. Any suggestions on how to remedy? Code below:
public static class ExcelPackageExtensions
{
public static DataTable ToDataTable(this ExcelPackage package)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
DataTable dt = new DataTable();
dt.Columns.Add("Email");
dt.Columns.Add("TimeStamp");
foreach (var firstRowCell in worksheet.Cells[1,1,1,worksheet.Dimension.End.Column])
{
dt.Columns.Add(firstRowCell.Text);
}
for (var rownumber=2; rownumber <= worksheet.Dimension.End.Row; rownumber++)
{
var row = worksheet.Cells[rownumber, 1, rownumber, worksheet.Dimension.End.Column];
var newrow = dt.NewRow();
newrow["Email"] = System.Web.HttpContext.Current.User.Identity.GetUserId();
newrow["TimeStamp"] = DateTime.Now;
foreach (var cell in row)
{
newrow[cell.Start.Column - 1] = cell.Text;
}
dt.Rows.Add(newrow);
}
return dt;
}
}

read from excel file to datatable asp.net

I got this code to read from a excel file after uploading
public static DataTable getDataTableFromExcel(string path)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
tbl.Rows.Add(row);
}
return tbl;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Uploader/") + filename);
err.Text = "Upload status: File uploaded!";
DataTable dt = getDataTableFromExcel(Server.MapPath("~/Uploader/") + filename);
GridView1.DataSource = dt;
GridView1.DataBind();
err.Text = dt.Rows[1].ToString();
}
catch (Exception ex)
{
err.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
but i cannot understand it well ... if you could give me a little description about it ?
and how to read specific column
I need to read just the first and third and fifth column not all ... how to do that ?

How to Convert pdf file to datatable

Is there any way to convert PDF file to DataTable? The PDF file mainly consist of only tables any help will be highly appreciated.
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
public DataTable ImportPDF(string Filename)
{
string strText = string.Empty;
List<string[]> list = new List<string[]>();
string[] PdfData = null;
try
{
PdfReader reader = new PdfReader((string)Filename);
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
String cipherText = PdfTextExtractor.GetTextFromPage(reader, page, its);
cipherText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(cipherText)));
strText = strText + "\n" + cipherText;
PdfData = strText.Split('\n');
}
reader.Close();
}
catch (Exception ex)
{
}
List<string> temp = PdfData.ToList();
temp.RemoveAt(0);
list = temp.ConvertAll<string[]>(x => x.Split(' ').ToArray());
List<string> columns = list.FirstOrDefault().ToList();
DataTable dtTemp = new DataTable();
columns.All(x => { dtTemp.Columns.Add(new DataColumn(x)); return true; });
list.All(x => { dtTemp.Rows.Add(dtTemp.NewRow().ItemArray = x); return true; });
return dtTemp;
}
If the PDF contains marked content (you can see how to find this in my blog article http://www.jpedal.org/PDFblog/2010/09/the-easy-way-to-discover-if-a-pdf-file-contains-structured-content/) you can extract it from the PDF file. Otherwise you will need to extract the text and try to guess the structure.

Resources