How to read excel file in asp.net other than OleDbConnection - c#

How can I read the excel sheet data in ASP.net without using OleDbConnection. I have tried OleDbConnection already but I am facing issues with it.
Are there any other ways to do so?

You need EPPlus for this kind of work. Site

Check this. It can read an excel file without OleDbConnection

you can use LinqToExcel to do this. following code will help a bit:
public ActionResult fileread()
{
var excel = new ExcelQueryFactory(#"File Name");
excel.AddMapping<ABC>(x => x.S1, "code"); // ABC is your database table name... code is the column name of excel file
excel.AddMapping<ABC>(x => x.S2, "description");
// you can map as many columns you want
var e = (from c in excel.Worksheet<ABC>("MyExcelFile") select c); // MyExcelFile is the name of Excel File's Sheet name
// similarly you can do whatever you want with the data like.. save to DB
foreach (var y in e)
{
ABC a = new ABC();
a.S1 = y.S1;
a.S2 = y.S2;
db.ABC.Add(a);
}
db.SaveChanges();
}

Related

how to resolve error while converting CSV to jason file

I have written the code with reference from one of the post on this forum but getting below error
my csv data as
how to proceed?
Before you can add data to a DataTable, you must add the columns you will need. You can also check if the column exists before adding it using dt.Columns.Contains.... If your CSV file has a header row you can use that to give your columns some header text.
Something like (this compiles but not actually run):
var dt = new DataTable();
var rows = csvfile.Split('\n');
// Add the columns
var colHeaders = rows[0].Split(',');
foreach(var header in colHeaders)
{
dt.Columns.Add(header, typeof(string));
}
// now add the data rows
foreach(var row in rows.Skip(1))
{
if(!string.IsNullOrEmpty(row))
{
var data = row.Split(',');
foreach(var d in data)
{
dt.Rows.Add(d);
}
}
}
There are other examples available on the internet specifically for reading CSV files into DataTables (here's one).

Linq Update - Cannot perform runtime binding on a null reference

I'm using LinqToExcel along with C# to read data from a MS Excel spreadsheet and then update data records in my MS SQL database.
The Excel file has these headers: COURSE_ID, PROVIDER_COURSE_TITLE
My code is like this:
public class TestDataCourse
{
[ExcelColumn("PROVIDER_COURSE_TITLE")]
public string cTitle
{
get;
set;
}
}
///////////////////////////////
string pathToExcelFile = #"C:\\O_COURSES.xlsx";
ConnexionExcel ConxObject = new ConnexionExcel(pathToExcelFile);
//read data from excel
var query1 = (from a in ConxObject.UrlConnexion.Worksheet<TestDataCourse>("O_COURSES")
select a).Take(2000).ToList();
//Get data from MS SQL database that need updated
var courses = _courseService.GetAllCoursesFromDB().Take(100).ToList();
int count = 0;
foreach (var course in courses)
{
//Iterate through the excel doc and assign the
TestDataCourse fakeData = query1.Skip(count).Take(1).FirstOrDefault();
course.CourseTitle = fakeData.cTitle;
count++;
}
_courseService.Save();
When I run this code I can see that it does update some of the records in my database, but as the code execution continues, I get a Source Not Available tab open within my Visual Studio and a Cannot perform runtime binding on a null reference.
The null reference exception had me thinking that maybe there was some null data in the Excel doc, so I put this line of code into my for loop:
course.CourseTitle = fakeData == null ? "Course Test" : fakeData.cTitle;
But I still get the same problem.
Could anyone please help?
Thanks.

C# Winform Excel Reading through a query

this is my first time to ask question. So please be gentle on me :)
My problem is, I want to format an excel file generated by our time and attendance terminal. Here is the generated excel file and some description of my problem:
What I want to do is read that excel file using C# Winform and format it as the way way I need it.
My Problems are:
How can I select the sheet? I know that it is only one sheet but I don't know on how to point a sheet using OleDbConnection. Sample in OleDBConnection is "[Sheet1$]" to read a Sheet but I'm not sure on what sheet name will be generated from the terminal. Can we use index? For Example : "from [Sheet1&]" will be "from [0$]"?
Same as the first problem but in the excel column. How can I treat it as for example, "[0], 1".
Last problem, and will probably explain it all. what I really want to do is use OleDbConnection and my command will be look like this :
"SELECT DISTINCT [0$], Convert([1$], Date), MIN(Convert([1$], Time)), MAX(Convert([1$], Time)) FROM [0$] GROUP BY [0$], Convert([1$], Date)"
Note : [0$] and [1$], are the index of either the columns or the sheets
What I need need is to generate a file that will show the employees attendance that will format with date and there first Time IN for the Day and there last Time Out. Please Look the image below for the idea of the output.
I've try to search but I'm not able to find a solution that will fits on what I need.
Hope that anyone can help me. Thanks!
For question:
Q1: See code note, i have not way to fix this question, if anybody got please sharing to me.
Q2: Same as first, i have not way to using index by DateTableName(or Sheet Name) or Columns in SQL.
Q3: Using Linq. More about Linq samples https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
These steps are how to get the expected data:
Read all data from Excel file need to know Sheet Name;
Filter invalid data, because there are many columns value is empty, null or space-string but added to rows;
Query data using Linq.
Hope that my answer can help you.
Reference codeļ¼š
public void Test()
{
string filePath = $"{Environment.CurrentDirectory}//test20170206.xls";
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'";
//connection excel
OleDbConnection conn = new OleDbConnection(conStr);
conn.Open();
//get all sheel from excel file
DataTable tb = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow row in tb.Rows)
{
Console.WriteLine(row["TABLE_NAME"]);
//using index in row
for (int i=0;i p.Datetime).ToLongTimeString(), TimeMax = g.Max(p => p.Datetime).ToLongTimeString() };
}
public class Model20170206
{
public int Id { get; set; }
public DateTime Datetime { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
public string Value4 { get; set; }
}
Practice steps:
I using some test data like this:
1,2017-01-28 03:47:54,1,1,1,0
2,2017-01-29 04:58:18,1,0,2,0
3,2017-01-28 08:44:43,1,1,3,0
4,2017-01-28 05:47:56,1,0,4,0
0,2017-02-05 12:12:53,1,1,5,0
1,2017-01-31 12:02:24,1,0,6,0
2,2017-02-05 12:30:34,1,1,7,0
3,2017-02-04 02:30:08,1,0,8,0
4,2017-02-01 11:39:53,1,1,9,0
0,2017-02-05 07:45:58,1,0,10,0
1,2017-02-05 03:01:46,1,1,11,0
2,2017-02-02 09:22:17,1,0,12,0
3,2017-01-30 03:05:46,1,1,13,0
4,2017-02-04 09:02:21,1,0,14,0
0,2017-02-03 07:58:20,1,1,0,0
1,2017-01-29 07:53:48,1,0,1,0
2,2017-01-29 12:41:25,1,1,2,0
3,2017-02-06 02:58:50,1,0,3,0
4,2017-01-28 11:06:47,1,1,4,0
0,2017-02-04 10:40:18,1,0,5,0
1,2017-01-31 12:57:24,1,1,6,0
2,2017-02-03 12:28:38,1,0,7,0
3,2017-02-01 06:48:23,1,1,8,0
4,2017-01-28 12:42:59,1,0,9,0
0,2017-02-04 10:34:44,1,1,10,0
1,2017-02-06 06:38:31,1,0,11,0
2,2017-02-05 08:40:26,1,1,12,0
3,2017-01-31 01:56:32,1,0,13,0
4,2017-02-05 11:13:11,1,1,14,0
0,2017-01-29 10:34:58,1,0,0,0
1,2017-02-02 04:01:18,1,1,1,0
2,2017-02-06 01:08:09,1,0,2,0
3,2017-01-28 07:24:11,1,1,3,0
4,2017-02-02 08:25:50,1,0,4,0
0,2017-01-28 08:01:13,1,1,5,0
1,2017-02-03 08:33:10,1,0,6,0
2,2017-01-29 03:47:03,1,1,7,0
3,2017-02-05 12:36:56,1,0,8,0
4,2017-02-04 06:10:55,1,1,9,0
0,2017-01-29 05:13:43,1,0,10,0
1,2017-02-06 06:35:18,1,1,11,0
2,2017-01-31 08:23:25,1,0,12,0
3,2017-02-03 04:25:10,1,1,13,0
4,2017-01-31 04:31:34,1,0,14,0
0,2017-01-30 10:03:42,1,1,0,0
1,2017-01-30 11:07:57,1,0,1,0
2,2017-02-05 11:17:45,1,1,2,0
3,2017-02-02 12:59:56,1,0,3,0
4,2017-01-31 04:49:48,1,1,4,0
0,2017-02-02 01:02:05,1,0,5,0
1,2017-01-31 11:16:52,1,1,6,0
2,2017-02-03 09:53:51,1,0,7,0
3,2017-01-31 04:02:09,1,1,8,0
4,2017-01-28 05:06:38,1,0,9,0
0,2017-01-28 09:18:28,1,1,10,0
1,2017-02-01 04:26:56,1,0,11,0
2,2017-02-03 11:17:34,1,1,12,0
3,2017-02-06 09:09:23,1,0,13,0
4,2017-01-30 08:20:51,1,1,14,0
0,2017-02-05 06:42:01,1,0,0,0
1,2017-02-01 04:29:38,1,1,1,0
2,2017-02-02 05:28:21,1,0,2,0
3,2017-02-05 04:24:37,1,1,3,0
4,2017-01-31 07:59:14,1,0,4,0
0,2017-01-31 10:38:59,1,1,5,0
1,2017-02-06 03:01:17,1,0,6,0
2,2017-02-02 08:52:25,1,1,7,0
3,2017-02-02 07:47:35,1,0,8,0
4,2017-02-04 07:55:27,1,1,9,0
0,2017-02-06 12:32:50,1,0,10,0
1,2017-01-28 11:01:04,1,1,11,0
2,2017-01-30 01:12:09,1,0,12,0
3,2017-01-29 03:42:15,1,1,13,0
4,2017-02-05 07:00:44,1,0,14,0
0,2017-02-05 05:12:40,1,1,0,0
1,2017-01-28 11:28:18,1,0,1,0
2,2017-02-05 09:11:08,1,1,2,0
3,2017-01-29 09:11:08,1,0,3,0
4,2017-02-04 03:46:57,1,1,4,0
0,2017-02-02 06:21:06,1,0,5,0
1,2017-01-28 02:15:06,1,1,6,0
2,2017-01-31 02:34:50,1,0,7,0
3,2017-02-05 10:14:23,1,1,8,0
4,2017-01-31 05:05:26,1,0,9,0
0,2017-02-05 12:25:46,1,1,10,0
1,2017-02-05 07:15:07,1,0,11,0
2,2017-02-03 04:00:19,1,1,12,0
3,2017-02-06 03:25:13,1,0,13,0
4,2017-02-02 06:01:42,1,1,14,0
0,2017-02-03 04:41:57,1,0,0,0
1,2017-02-06 10:23:15,1,1,1,0
2,2017-01-29 07:45:19,1,0,2,0
3,2017-02-03 11:10:25,1,1,3,0
4,2017-02-05 12:36:33,1,0,4,0
0,2017-02-03 01:51:44,1,1,5,0
1,2017-02-01 08:01:16,1,0,6,0
2,2017-02-01 05:06:28,1,1,7,0
3,2017-01-31 03:20:15,1,0,8,0
4,2017-02-05 07:00:14,1,1,9,0
0,2017-01-31 08:10:04,1,0,10,0
1,2017-02-03 03:23:12,1,1,11,0
2,2017-01-31 10:24:29,1,0,12,0
3,2017-02-04 06:12:08,1,1,13,0
4,2017-01-31 05:24:38,1,0,14,0
0,2017-02-01 08:55:20,1,1,0,0
1,2017-01-29 04:59:03,1,0,1,0
2,2017-02-02 01:05:55,1,1,2,0
3,2017-02-01 10:09:05,1,0,3,0
4,2017-01-30 01:01:37,1,1,4,0
0,2017-02-06 10:57:49,1,0,5,0
1,2017-02-01 08:23:28,1,1,6,0
2,2017-02-01 09:00:45,1,0,7,0
3,2017-01-30 12:16:46,1,1,8,0
0,2017-02-04 06:06:36,1,0,10,0
1,2017-02-01 09:31:02,1,1,11,0
...
more
...
Import them into Excel File look like this :
My code result data like this :

Using OpenXML, how can I associate a list for data validation

I am processing an .xlsm file and need to know how to use a list on another sheet for data validation using openXML and C#.
To start, I have a .xlsm file with two empty sheets and macros in it. In my program I open the file, Create the column header on Sheet1 then create the validation list on sheet2. So, after I run my program Sheet1 "A1" contains the text "Color" and Sheet2 "A1:A4" contains "Blue","Green","Red","Yellow". I get this far just fine.
I would like to make it so there is a dropdown list in all cells of column "A" on sheet1 that contains each of the 4 colors and enforces them as the only input. In Microsoft Excel this is done by going to the "Data" tab, selecting "Data Validation" selecting "List" and highlighting the cells you want to use. I need to make this association programmatically.
The (Desired) XML that Microsoft Excel creates if I do it manually is this:
<extLst>
<ext uri="{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">
<x14:dataValidations count="1" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">
<x14:dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1">
<x14:formula1>
<xm:f>'Validation Data'!$A$1:$A$4</xm:f>
</x14:formula1>
<xm:sqref>A1:A1048576</xm:sqref>
</x14:dataValidation>
</x14:dataValidations>
</ext>
</extLst>
The following method and results is something I tried. It may give a better Idea of what I'm trying to do.
Here, I pass in "'Sheet2'!$A$1:$A$4" as the "validationListCells" parameter. This represents the cells in "Sheet2" that, in this example, would contain the color names "Red", "Green"...etc.
I pass in "A2:A1048576" as the "cellsToValidate" parameter. This represents all cells of Sheet1 column "A", on which I want to enforce validation.
I pass "Sheet1" as the worksheetName parameter.
private void InsertValidation(String worksheetName, String validationListCells, String cellsToValidate)
{
DataValidations dataValidations1 = new DataValidations() { Count = (UInt32Value)1U };
DataValidation dataValidation1 = new DataValidation()
{
Formula1 = new Formula1(validationListCells),
Type = DataValidationValues.List,
ShowInputMessage = true,
ShowErrorMessage = true,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = cellsToValidate }
};
dataValidations1.Append(dataValidation1);
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(_documentPath, true))
{
WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, worksheetName);
worksheetPart.Worksheet.Append(dataValidations1);
worksheetPart.Worksheet.Save();
}
}
It results in this XML in Sheet1.xml. Which causes an error in Excel.
<x:dataValidations count="1">
<x:dataValidation type="list" showInputMessage="1" showErrorMessage="1" sqref="A2: A1048576">
<x:formula1>'Sheet2'!$A$1:$A$5</x:formula1>
</x:dataValidation>
</x:dataValidations>
It looks like I may be on the right track since it is beginning to resemble the xml created by Excel, but I'm completely new to openXML and I'm finding little about this topic on the net.
Thanks in advance!
For anyone else in need of this..the code below worked for me.
I put in there user3251089's variable names.
In general, when I try to programmatically create an excel "feature" I manually make a really basic excel that has in it that feature (delete extra sheets too). Then I reflect the code and try to make it prettier.
hope it serves to someone!
using Excel = DocumentFormat.OpenXml.Office.Excel;
using X14 = DocumentFormat.OpenXml.Office2010.Excel;
.....
Worksheet worksheet = worksheetPart.Worksheet;
WorksheetExtensionList worksheetExtensionList = new WorksheetExtensionList();
WorksheetExtension worksheetExtension = new WorksheetExtension() { Uri = "{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}" };
worksheetExtension.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
X14.DataValidations dataValidations = new X14.DataValidations() { Count = (UInt32Value)3U };
dataValidations.AddNamespaceDeclaration("xm", "http://schemas.microsoft.com/office/excel/2006/main");
//sites validation
dataValidations.Append(new X14.DataValidation()
{
Type = DataValidationValues.List,
AllowBlank = true,
ShowInputMessage = true,
ShowErrorMessage = true,
DataValidationForumla1 = new X14.DataValidationForumla1() { Formula = new Excel.Formula(validationListCells) },
ReferenceSequence = new Excel.ReferenceSequence(cellsToValidate)
});
worksheetExtension.Append(dataValidations);
worksheetExtensionList.Append(worksheetExtension);
worksheet.Append(worksheetExtensionList);
worksheet.Save();

Inserting XML document into SQL column using linq

I have a column in one of my SQL tables that is of type XML. I want to insert an entire XML file into one of the cells of this column from the back-end using linq. There are a few similar questions to this, but none of them have been much help to me.
Thanks in advance.
EDIT:
Well I really haven't made it very far, but here is a rough idea of what I'm trying to do.
StagingDBDataContext ctx = new LoaderCommon.StagingDBDataContext();
upload_info ups = (from u in ctx.upload_infos where u.upload_id == info.upload_id select u).SingleOrDefault();
ups.upload_params = //xml text (huge file, 50,000 lines long)
When you put it on SqlXml just read xml as string
private string LoadXml(string FileName)
{
try
{
using (StreamReader reader = new StreamReader(FileName))
{
return reader.ReadToEnd();
}
}
catch
{
return string.Empty;
}
}

Categories

Resources