Can not read Excel File using NuGet FileHelpers.ExcelNPOIStorage - c#

I have a problem with reading file using ExcelNPOIStorage.
Error Code:
System.MissingFieldException: 'Field not found: 'NPOI.SS.UserModel.MissingCellPolicy.CREATE_NULL_AS_BLANK'.'
Code:
var filesList = "test.xlsx";
string folderPath = System.IO.Path.GetFullPath(#"..\..\SyncFiles");
string filePath = Path.Combine(folderPath, file);
if (File.Exists(filePath))
{
DataTable dTable = new DataTable();
var provider = new ExcelNPOIStorage(typeof(Mac))
{
StartRow = 2,
StartColumn = 1,
FileName = filePath,
SheetName = "Sheet1"
};
var res = (Mac[])provider.ExtractRecords();
}
Mac Class:
[DelimitedRecord("|")]
class Mac
{
public int PropertyID;
public string ID;
public string Name;
}
test.xlsx

Related

Loading tsv/csv file in excel sheet

This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default

How to save exported excel at server directory

I want to export data table in Excel sheet and saving in server directory in MVC application. Here is my code-
//ManagEmployeeController.cs
public JsonResult ExportToExcel()
{
Excel.ExcelUtlity obj = new Excel.ExcelUtlity();
DataTable dt = ConvertToDataTable(ListEmployee());
string dir = string.Format("~/Clients/ExportedData/");
var directoryToSaveFile = Server.MapPath(dir);
string uniqueNumber = DateTime.Now.ToString("yyyyMMddHHmmss");
string file = "ContactExportData.xlsx";
string newFileName = string.Format("{0}{1}", uniqueNumber, file);
if (!Directory.Exists(directoryToSaveFile))
{
Directory.CreateDirectory(directoryToSaveFile);
}
string fullFilePath = string.Format("{0}/{1}",dir,newFileName); ;
//obj.WriteDataTableToExcel(dt, "Person Details", "D:\\testPersonExceldata.xlsx", "Details");
obj.WriteDataTableToExcel(dt, "Person Details", fullFilePath, "Details");
var result = new { Success = "Success", Messaage = "SuccessMessage" };
return Json(result,JsonRequestBehavior.AllowGet);
}
The directory gets created but file does not saved here. But if I use commented code(obj.WriteDataTableToExcel(dt, "Person Details", "D:\\testPersonExceldata.xlsx", "Details");) the file gets saved on my local directory D.
//ExcelUtility.cs
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)
{
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
//
//
excelworkBook.SaveAs(saveAsLocation);;
}
What is missing in my code in order to save Excel to mentioned directory on server?
string fullFilePath = string.Format("{0}/{1}",dir,newFileName);
should be:
string fullFilePath = string.Format("{0}/{1}",directoryToSaveFile,newFileName);

How to save multiple image names into database by using dropzone?

I am using dropzone to upload the images. image will be uploaded to server folder while image name will be saved in database table.
here is my code :
public class FormUploader_dz : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("/images/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
Service.SaveImage(strFileName, context.Session["Id"].ToString());
}
}
context.Response.Write(str_image);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Service file code : which will insert image name into table.
public static void SaveImage(string strImage, string Id)
{
string strSql = #"update tablename set image=#image where id=#Id
";
SqlParameter[] objSqlParameter ={
new SqlParameter("#image",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}
Now here problem is i have 4 columns in table to save 4 different image name. what i am actually doing is allowing user to upload max 4 images. i have 4 columns as img1, img2, img3, img4.
here how to insert/update image name into table, as their are 4 diffrent columns for images!
here if user wants he can upload 4 images. so how to decide that in which column the image name will go?????
any suggestions??????
I am not sure about the exact syntax but something like this could work.
// **********************************
int counter = 0; // set up the counter
// **********************************
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
// **********************************
counter++; // increment the counter
// **********************************
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
// **********************************
Service.SaveImage(strFileName, context.Session["Id"].ToString(), counter); // add counter variable to the path.
// **********************************
}
}
// **********************************
// add a column variable and then add it to your column name. like string columnName = "img+columnCount"
// **********************************
public static void SaveImage(string strImage, string Id, int columnCount)
{
// **********************************
string strSql = #"update tablename set img#columnName=#image where id=#Id";
// **********************************
SqlParameter[] objSqlParameter ={
new SqlParameter("#strImage",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}

How can I get values from a csv file where some of the cells contain commas?

I have a script that imports a csv file and reads each line to update the corresponding item in Sitecore. It works for many of the products but the problem is for some products where certain cells in the row have commas in them (such as the product description).
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (UpdateFile.PostedFile != null)
{
var file = UpdateFile.PostedFile;
// check if valid csv file
message.InnerText = "Updating...";
Sitecore.Context.SetActiveSite("backedbybayer");
_database = Database.GetDatabase("master");
SitecoreContext context = new SitecoreContext(_database);
Item homeNode = context.GetHomeItem<Item>();
var productsItems =
homeNode.Axes.GetDescendants()
.Where(
child =>
child.TemplateID == new ID(TemplateFactory.FindTemplateId<IProductDetailPageItem>()));
try
{
using (StreamReader sr = new StreamReader(file.InputStream))
{
var firstLine = true;
string currentLine;
var productIdIndex = 0;
var industryIdIndex = 0;
var categoryIdIndex = 0;
var pestIdIndex = 0;
var titleIndex = 0;
string title;
string productId;
string categoryIds;
string industryIds;
while ((currentLine = sr.ReadLine()) != null)
{
var data = currentLine.Split(',').ToList();
if (firstLine)
{
// find index of the important columns
productIdIndex = data.IndexOf("ProductId");
industryIdIndex = data.IndexOf("PrimaryIndustryId");
categoryIdIndex = data.IndexOf("PrimaryCategoryId");
titleIndex = data.IndexOf("Title");
firstLine = false;
continue;
}
title = data[titleIndex];
productId = data[productIdIndex];
categoryIds = data[categoryIdIndex];
industryIds = data[industryIdIndex];
var products = productsItems.Where(x => x.DisplayName == title);
foreach (var product in products)
{
product.Editing.BeginEdit();
try
{
product.Fields["Product Id"].Value = productId;
product.Fields["Product Industry Ids"].Value = industryIds;
product.Fields["Category Ids"].Value = categoryIds;
}
finally
{
product.Editing.EndEdit();
}
}
}
}
// when done
message.InnerText = "Complete";
}
catch (Exception ex)
{
message.InnerText = "Error reading file";
}
}
}
The problem is that when a description field has commas, like "Product is an effective, preventative biofungicide," it gets split as well and throws off the index, so categoryIds = data[8] gets the wrong value.
The spreadsheet is data that is provided by our client, so I would rather not require the client to edit the file unless necessary. Is there a way I can handle this in my code? Is there a different way I can read the file that won't split everything by comma?
I suggest use Ado.Net, If the field's data are inside quotes and it will parse it like a field and ignore any commas inside this..
Code Example:
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = #"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}

Parsing CSV file with type

I am trying to parse a CSV and construct a DataTable out of it. Now the tricky part is i would like to assign data types before constructing the data table.
For eg consider the following CSV file
Name,Age,Salary
A,30,1000
B,35,1500
C,40,2000
I would like to have Name stored as string, Age as Int and Salary as decimal in the data table I am constructing. Any suggestions on the best way to do this?
Here's a naive implementation that ignores most error checking, and some good coding practices:
namespace StackOverflowConsole
{
using System;
using System.IO;
using System.Data;
class Program
{
static void Main(string[] args)
{
var path = #"C:\temp\test.csv";
CreateTestFile(path);
var dataTable = new DataTable();
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Age", typeof(int));
dataTable.Columns.Add("Salary", typeof(decimal));
// TODO: add checks, exception handling
using (var reader = new StreamReader(path))
{
// reads all lines into a single string
var lines = reader.ReadToEnd().Split(new char[] { '\n' });
if (lines.Length > 0)
{
// you may wanna skip the first line, if you're using a file header
foreach (string line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
// split the current line using the separator
var tokens = line.Trim().Split(new char[] { ',' });
// check your assumptions on the CSV contents
// ex: only process lines with the correct number of fields
if (tokens.Length == 3)
{
var person = new Person();
person.Name = tokens[0];
// a better implementation would use TryParse()
person.Age = Int32.Parse(tokens[1]);
person.Salary = Decimal.Parse(tokens[2]);
dataTable.Rows.Add(person.Name, person.Age, person.Salary);
}
}
}
}
}
private static void CreateTestFile(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
using (var writer = new StreamWriter(path))
{
writer.WriteLine("A,30,1000");
writer.WriteLine("B,35,1500");
writer.WriteLine("C,40,2000");
}
}
}
public class Person
{
public string Name;
public int Age;
public decimal Salary;
}
}
Try this:
Keep CSV file in code directory
string path = Server.MapPath("emp.csv");
string header = "Yes";
string sql = string.Empty;
DataTable dt = null;
string fullpath = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";Extended Properties=\"Text;HDR=" + header + "\"");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + fileName + "]", connection);
dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Salary", typeof(decimal));
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();

Categories

Resources