reading xlsx with multi sheets into lists c# - c#

I have a code where i read a file (.csv) and store its columns in lists.
var pathskill = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), "skill.csv");
using (var fs1 = File.OpenRead(pathskill))
using (var reader1 = new StreamReader(fs1))
while (!reader1.EndOfStream)
{
var line = reader1.ReadLine();
var values = line.Split(',');
list_MainId.Add(Convert.ToDouble(values[0]));
list_MainName.Add(values[1]);
list_AmountMade.Add(Convert.ToInt32(values[2]));
list_Level.Add(Convert.ToDouble(values[3]));
list_Exp.Add(Convert.ToDouble(values[4]));
list_MadeFrom_One_Id.Add(Convert.ToDouble(values[5]));
list_Amount_MadeFrom_One.Add(Convert.ToInt32(values[6]));
list_MadeFrom_Two_Id.Add(Convert.ToDouble(values[7]));
list_Amount_MadeFrom_Two.Add(Convert.ToInt32(values[8]));
}
This code works great and i get 9 lists with values.
However, i have many .csv files and i think it will be better that each will be like a sheet in xlsx file and i can choose which one to read by its name.
For example to have a sheet called skill1, skill2 and so on.
Is there a way to read a specific sheet from xlsx by its name and store it columns into lists?
Thank you

There are a lot of ways to do this. You could unzip xlsx files and read sheet XMLs directly, or you may use some library that can work with xlsx (e.g. EPPLUS that is freeware).

Related

Parsing excel sheet - cell by cell

I would like to see your help on how to parse an excel file in mvc c# but, accessing its cell address like:
var a = Excel_cell{A1:B1}
model.a = a
I've looked to various plugin like excelfilereader, epplus and also javascript libraries like sheetjs and alike but, they do the same where they parse the whole file with the layout of a table...
My excel file is quite complicated because it has no headers and its data is on the right side.
EG:
I apologize if I put an image here...
My requirement is read an excel template, and save its data to the database.. I dont need to send the file to server because it will not be beneficial in the long run
Im hoping you could help me... An idea how to accomplish this would be really help.
You can try by using Spire.XLS, It's a good library that helps you read and write (this one only with a license) excel files and some other formats, it's easy to use and intuitive, for example this would be the code to get an excel file and read some cells:
//Create a variable to access the excel file
Workbook yourFile = new Workbook();
Stream stream = new MemoryStream(FilePath);
//Load the excel file into the variable
workbook.LoadFromStream(stream);
//Select the worksheet you want to take values from
var firstSheet = workbook.Worksheets.Where(x => x.Name == "Name of the sheet").First() as Worksheet;
string value = firstsheet.Range[A1].Text;
So with this code you have populated a variable with the excel file, a variable with a specific sheet (for example the first one), and then you save the text value of a specific cell of your choice in another variable, let me know if I got it right
EDIT: This is their site and this is the nuget gallery

How to merge csv and excel?

I am trying to build simple program that does my weekly job.
Everytime I receive csv file, I maintain excel file.
My csv is like below:
key_code,eng_name,...so on
000001,some name,...so on
My excel is like below:
Some text are written on A1-G4
No column hearders written
Data is from 5th row
Each row has data from B-G(1st row B5-G5, 2nd row B6-G6)
If key_code in csv does not exist in excel, I add.
If key_code in csv does exist in excel, I update the rest columns.
If key_code in excel does not exist in csv, I delete the row.
Can anyone tell me any easy way or steps to get this done?
I am very confusing about what to use to update excel file among OleDb, Interop.Excel, epplus, spire.xls, etc.
And in which class do I have to store csv data and excel data to compare.
For reading CSV you can use ChoETL reader, this is one of the best CSV readers I have ever used.
The tricky part is to how to write Excel file and choosing the right tool, amongst the tools you have mentioned EPPlus is best because
Excel.Interop needs Excel(MS Office) to be installed on production machine which can create licencing issues
To use OleDB you need some nitty gritty to use it a better way
EPPlus provides some abstraction which makes it easy to manipulate the excel files
using (var p = new ExcelPackage())
{
//A workbook must have at least on cell, so lets add one...
var ws=p.Workbook.Worksheets.Add("MySheet");
//To set values in the spreadsheet use the Cells indexer.
ws.Cells["A1"].Value = "This is cell A1";
//Save the new workbook. We haven't specified the filename so use the Save as method.
p.SaveAs(new FileInfo(#"c:\workbooks\myworkbook.xlsx"));
}
This is very simple example given on the github page to write, please use it and post any specific issues
If key_code in csv does not exist in excel, I add.
If key_code in csv does exist in excel, I update the rest columns.
If key_code in excel does not exist in csv, I delete the row.
As my understanding of the rules above, you simply delete the old excel file and create a new file from the data in the CSV file.
You can use R to do this very easily:
#Install package 'writexl' if you didn't, by install.packages("writexl")
library(writexl)
#File excel
fn <- "file.xlsx"
#Check its existence
if (file.exists(fn))
#Delete file if it exists
file.remove(fn)
#Read the csv file to a data frame
df <- read.csv("C:/newfile.csv")
#Write the data frame to excel file. Change col_names = TRUE if you want the headers.
write_xlsx(
df,
path = "file.xlsx",
col_names = FALSE
)

Make an array from all Excel worksheets

I have a C# code that connects to Excel database via OpenFileDialog func. Excel file has too many worksheets and I would like to get all their names in one array and add them to combobox.
For example, this one is the first Excel document.
Any suggestions?
You could try the following:
Accord.IO.ExcelReader reader = new Accord.IO.ExcelReader("yourFile.xlsx");
string[] worksheets = reader.GetWorksheetList();
make sure to include
using Accord.IO;
which you can get Accord from NuGet by searching Accord and Accord.IO.
Then just fill in the items of the Combo box
foreach (string worksheet in worksheets)
{
myComboBox.Items.Add(worksheet);
}

Search text in particular column and retrieve data from another column in excel using C#

I have an Excel file of 20 columns and there are about 150 records. I need to search for a particular string in a particular column with header "DESCRIPTION"(usually column b). The search string and column header values come from an INI File. After the search is found, I need to copy the value in column J (again from INI file) to the output file.
I am new to C#. Can somebody help me here. I tried Range.Find but I got confused.
Usually OLEDB with SQL like statements can be used to retrieve specific column or row data. Please go throgh following solutions:
http://www.c-sharpcorner.com/UploadFile/6b8651/read-excel-file-in-windows-application-using-C-Sharp/
https://www.codeproject.com/articles/1088970/read-write-excel-file-with-oledb-in-csharp-without
Hope this will give you some idea. But try to show some of your code so that members can have the better understanding of your approach. Thanks
Apart from Oledb connection you can also use ClosedXML. ClosedXML is a wrapper around OpenXML that allows you to easily work with .XLSX files.
https://github.com/ClosedXML/ClosedXML.
You can look at the documentation that'll help you understand how to search for text.
If you want to search .XLS files, then you can use the Microsoft Excel Interoperability libraries. These libraries cannot be used in a web app, are slower than ClosedXML but they support all kinds of Excel files.
You can use free version of GemBox.Spreadsheet to search for a text in both XLS and XLSX file formats. Also regarding the INI file, you can use MadMilkman.Ini.
Here is an example that you could try:
// Load INI file.
IniFile ini = new IniFile();
ini.Load("Sample.ini");
// Get INI values.
string header = ini.Sections["SampleSection"].Keys["ColumnHeaderValue"].Value;
string search = ini.Sections["SampleSection"].Keys["SearchTextValue"].Value;
string j = ini.Sections["SampleSection"].Keys["JColumnValue"].Value;
// Load XLSX file.
ExcelFile excel = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet sheet = excel.Worksheets[0];
// Find column header value in first row.
ExcelColumn searchColumn = sheet.Rows[0].Cells
.First(cell => cell.ValueType == CellValueType.String && cell.StringValue == header)
.Column;
// Find search value in column.
int r, c;
searchColumn.Cells.FindText(search, false, false, out r, out c);
ExcelCell searchCell = sheet.Cells[r, c];
// Get cell from column "J" that is in the same row as cell that has search text.
ExcelCell jCell = sheet.Cells[r, ExcelColumnCollection.ColumnNameToIndex("J")];
// Set cell value.
jCell.Value = j;
// Save XLSX file.
excel.Save("Sample.xlsx");

How can I read csv file into textboxes?

I am new to programing and I would like to read a csv file into textboxes that I have on a form. Right now I am reading the file into a dataTable and was thinking I would then read it into the texboxes but I am not sure if I am going about this correct. Is there an easier way to do this? This is what I have so far:
protected void getftp()
{
//create Data table to temporary storage
var myTable = new DataTable();
//add columns
myTable.Columns.Add("Start_date");
myTable.Columns.Add("End_date");
//...snip...
myTable.Columns.Add("Comments");
//The 'using' command close connection when it is done
using (var reader = new StreamReader(File.OpenRead(#"C:\ftp\inbox\test.csv")))
{
while (!reader.EndOfStream)
{
//read in one line of the file
string line = reader.ReadLine();
//create an array of strings from each value in the current line
string[] values = line.Split(',');
//add the array as a row in the DataTable
myTable.Rows.Add(values);
}
}
}
see the following link. It shows the basics of working with th CSV format http://www.codeproject.com/Articles/30705/C-CSV-Import-Export
Here is another SO Question regarding reading CSV Files in .NET:
Reading a CSV file in .NET?
This particular answer references 2 CSV Readers. You could use these to read in the CSV file and then set the values in your Textboxes on your Windows Form (or Web Form or ASPX or Razor page, you did not indicate your front-end).
I would recommend reusing one of these projects instead of re-inventing the wheel and rolling your own CSV parser. It's easy enough to write in C#, but reading/parsing CSV files is a problem that has been solved many times over.

Categories

Resources