I have an excel sheet with a single column of data.
I've only really done it with a csv but I've forgotten how to do it with a single row. I can't seem to get it to work. What I have now with what I think is right but is not working.
List<string> strList = new List<string>();
var reader = new StreamReader(File.OpenRead(#"C:\vcl\CompletionTest.xlsx"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var value = reader[0].ToString();
strList.Add(values[0]);
}
Please and thank you!
Related
All,
Been trying to figure this out for a day now. Did a lot of googling!
I have an excel where I have 5 columns but in first column I have product numbers. I want to return DISTINCT product numbers from the excel. Using EPPlus to read in the excel. Here is my code:
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
if (file.FileName.IndexOf(".xlsx") == 0)
{
throw new Exception("Please ensure that the file has been converted to latest excel version. The file type must be .xlsx.");
}
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.FirstOrDefault();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
//lets remove all records
//get a list of distinct item numbers and remove all records in preparation for upload
//I need help with this statement!
var result = workSheet.Cells.Select(grp => grp.First()).Distinct().ToList();
So I was able to figure it out by debugging. This doesnt seem to be the most efficient answer but here it goes:
var result = workSheet.Cells.Where(s => s.Address.Contains("A")).Where(v => v.Value != null).Where(vb => vb.Value.ToString() != "").GroupBy(g => g.Value.ToString()).Distinct().ToList();
So basically return Only column A (First column since address holds this information) then eliminate nulls and blanks, next group by the value and finally return distinct as a list.
Regarding your answer (sorry not enough rep to comment):
workSheet.Cells.Where(s => s.Address.Contains("A")).....
That could include ZA, AA, etc If you just want column A you could do
workSheet.Cells[1,1,workSheet.Dimension.End.Row, 1].....
This will start at A1, and just look down column A till the end. You'll still might need to filter null, blank etc, or if you need to start at row 5 here is all i needed. exmaple:
workSheet.Cells[5,1,workSheet.Dimension.End.Row, 1].GroupBy(g => g.Value.ToString()).Distinct().ToList();
I've been struggling with a small piece of code for a little while now. I have a CSV file with one column that contains a string of numbers. I can import that file without issues and display it.
My goal is to take the numbers in each of the tables and put it into a separate string, run that string through a function and then put the results back into my datagrid in column two. Is there a way that I should be doing this using the code below; the foreach statement is where I believe this should be done.
Edit: I tweaked the code and it now works the way that I want it to but I can't insert my result into any columns except for the first one. Is there a way that I should be targeting the results so they go in the second column?
using (var fs = File.OpenRead(Dialog.FileName))
using (var reader = new StreamReader(fs))
{
List<string> lista = new List<string>();
List<string> listb = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
lista.Add(values[0]);
dt1.Rows.Add(values[0]);
}
foreach (var item in lista)
{
string temp;
GetLuhnCheckDigit(item);
listb.Add(last.ToString());
temp = item + last.ToString();
dt1.Rows.Add(temp); //This only adds to the first column
}
dataGridView1.DataSource = dt1;
Without knowing what GetLuhnCheckDigit method does, it is not possible to determine what values you want the second column to contain. Looking at the posted code, there are many things missing like how many columns the data table has, where is the Dialog variable definition? What is last?
Assuming there are at least two columns in the DataTable dt1, I am not sure why you are adding the items to the first column then loop through a list of those items to set the second column. It appears adding both of the columns at the same time would be easier.
You could do all this while reading the file like below:
try {
using (var fs = File.OpenRead(Dialog.FileName)) {
using (var reader = new StreamReader(fs)) {
List<string> lista = new List<string>();
List<string> listb = new List<string>();
string temp;
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(',');
lista.Add(values[0]);
GetLuhnCheckDigit(values[0]); // <-- What is this method doing???
listb.Add(last.ToString());
temp = values[0] + last.ToString();
dt1.Rows.Add(values[0], temp); // <-- this adds both columns
}
dataGridView1.DataSource = dt1;
}
}
}
catch (Exception e) {
MessageBox.Show("Error: " + e.Message);
}
Let me know if I am missing something, as I am clueless as to what the GetLuhnCheckDigit method could be doing.
Simply put: I need to read from an xlsx file (rows), in the simplest way. That is, preferably without using third-party tools, or at least things that aren't available as nuget packages.
I've been trying for a while with IExcelDatareader, but I cannot figure out how to get data from a specific sheet.
This simple code snippet works, but it just reads the first worksheet:
FileStream stream = File.Open("C:\\test\\test.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
while (excelReader.Read()) {
Console.WriteLine(excelReader.GetString(0));
}
This prints the rows in the first worksheet, but ignores the others. Of course, there is nothing to suggest otherwise, but I cannot seem to find out how to specify the sheet name.
It strikes me that this should be quite easy?
Sorry for asking something which has been asked several times before, but the answer (here and elsewhere on the net) are a jungle of bad, plain wrong and outdated half-answers that's a nightmare to try and make sense of. Especially since almost everyone answering assumes that you know some specific details that are not always easy to find.
UPDATE:
As per daniell89's suggestion below, I've tried this:
FileStream stream = File.Open("C:\\test\\test.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
// Select the first or second sheet - this works:
DataTable specificWorkSheet = excelReader.AsDataSet().Tables[1];
// This works: Printing the first value in each column
foreach (var col in specificWorkSheet.Columns)
Console.WriteLine(col.ToString());
// This does NOT work: Printing the first value in each row
foreach (var row in specificWorkSheet.Rows)
Console.WriteLine(row.ToString());
Printing each column heading with col.ToString() works fine.
Printing the first cell of each row with row.ToString() results in this output:
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
...
One per row, so it's obviously getting the rows. But how to get the contents, and why does ToString() work for the columns and not for the rows?
Maybe look at this answer: https://stackoverflow.com/a/32522041/5358389
DataSet workSheets= reader.AsDataSet();
And then specific sheet:
DataTable specificWorkSheet = reader.AsDataSet().Tables[yourValue];
Enumerating rows:
foreach (var row in specificWorkSheet.Rows)
Console.WriteLine(((DataRow)row)[0]); // column identifier in square brackets
You need to get the Worksheet for the sheet you want to read data from. To get range A1 from Cars, for example:
var app = new Application();
Workbooks workbooks = app.Workbooks;
Workbook workbook = workbooks.Open(#"C:\MSFT Site Account Updates_May 2015.xlsx");
Worksheet sheet = workbook.Sheets["Cars"];
Range range = sheet.Range["A1"];
It is a late reply but i hope it will help someone
The script will be aiming at retrieving data from the first sheet and also to get the data of the first row
if (upload != null && upload.ContentLength > 0)
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
Stream stream = upload.InputStream;
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
ModelState.AddModelError("File", "This file format is not supported");
return View();
}
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
}).Tables[0];// get the first sheet data with index 0
var tables = result.Rows[0].Table.Columns;//we have to get a list of table headers here "first row" from 1 row
foreach(var rue in tables)// iterate through the header list and add it to variable 'Headers'
{
Headers.Add(rue.ToString());//Headers has been treated as a global variable "private List<string> Headers = new List<string>();"
}
var count = Headers.Count();// test if the headers have been added using count
reader.Close();
return View(result);
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}
I have array string list that is actually a csv file that every filed of this list is a file row .
In this csv file (List) i have more then 20 columns and i need to create a new list that will contain only specific columns from the original list .
how can i do that ?
this is the list:
List<string[]> parsedData = new List<string[]>();
parsedData = ParseResultCSV();
Every cell in a CSV file is separated with a ';'.
So something like this:
var listOfParsedValues = new List<List<string>>();
foreach(var row in parsedData){
var cells = row.Split(';');
// if you for example want to save values at cell 4 and 7:
var valuesOfThisRow;
valuesOfThisRow.Add(cells[4]);
valuesOfThisRow.Add(cells[7]);
listOfParsedValues.Add(valuesOfThisRow);
}
Not optimal, but it works :)
I would like to find the last row of the datagridview and i would like to write that particular row data to a text file can any one help me
I will give you a sample code, it may help.
List<string> lstContents = new List<string>();
foreach (DataGridViewCell cell in mydataGrid.Rows[mydataGrid.RowCount - 1].Cells)
{
lstContents .Add((string)cell.Value);
}
string myData= string.Join(",", lstContents.ToArray());
Now using streamwriter you can write this string to your file. Also you can use any separator. I have used "," comma here.
///This will append data to your text file...
using (StreamWriter sw = new StreamWriter(FilePath, true))
{
sw.WriteLine(myData);
}