How to read two sheet from CSV file - c#

I have two sheets in CSV excel file which I upload using the following code. But from this code it reads only the first sheet. Even httpRequest.Files.Count returns only 1. How to read both sheet of the file
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
long dataSourceId = 1;
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
//postedFile.SaveAs(filePath);
Stream stream = postedFile.InputStream;
byte[] fileData = null;
using (var binaryReader = new BinaryReader(postedFile.InputStream))
{
fileData = binaryReader.ReadBytes(postedFile.ContentLength);
}
Stream strrr = new MemoryStream(fileData);
}
}

From what I can tell CSV files aren't workbooks like Excel files, so you won't be about to read CSV file with two sheets as two entities on a single file. This is why I came to that conclusion:
http://network.ubotstudio.com/forum/index.php/topic/3236-save-in-multiple-sheets-in-a-csv-file/
You have two options: 1) Create multiple CSV files with the needed data and read from them individually OR 2) Use an Excel file that is formatted to handle these multiple sheet features.

Related

Reading data in a SpreadsheetDocument from MemoryStream

I have a page on my site where a user can upload a XLSX spreadsheet. This is a .NET Core web application using the DocumentFormat.OpenXml (2.15.0) NuGet package.
I'm trying to read through each row in the spreadsheet they upload and do something with that data. I'm trying to do this without saving a physical file by copying the file to a MemoryStream, then reading the file from that stream, but not sure if that's possible.
The problem is that when reading the doc from the stream, it's like there's no data in the spreadsheet
Here's what I have:
using (var memoryStream = new MemoryStream())
{
await viewModel.SpreadsheetFile.CopyToAsync(memoryStream).ConfigureAwait(false);
// confirm that copying to memory stream worked correctly
var fileBytes = memoryStream.ToArray();
string s = Convert.ToBase64String(fileBytes);
using (SpreadsheetDocument document = SpreadsheetDocument.Open(memoryStream, true))
{
WorkbookPart workbook = document.WorkbookPart;
WorksheetPart worksheet = workbook.WorksheetParts.First();
SheetData sheetData = worksheet.Worksheet.Elements<SheetData>().First();
string text;
// no rows, doesn't enumerate here
foreach (Row r in sheetData.Elements<Row>())
{
foreach (Cell c in r.Elements<Cell>())
{
text = c.CellValue.Text;
// do stuff
}
}
}
}
I added a couple lines to read bytes from the memory stream just to confirm that it's working, which it is.
But when I try to create a SpreadsheetDocument from the memory stream and read the sheet data, it's just empty, it doesn't enumerate through the rows.
The code to read the sheet data I got from here: https://learn.microsoft.com/en-us/office/open-xml/how-to-parse-and-read-a-large-spreadsheet
Is this possible, or am I just doing this wrong?
You need to set memory stream to zero after reading to it. Change code to this:
await viewModel.SpreadsheetFile.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Position = 0;

How to read incoming excel file in base64 and extract their data in C# asp.net

I am making an API using C# that takes excel files and transforms and saves its data to database.
I am transforming the excel sheet to base64 and then convert it using epplus to excel sheet.
Problem:
I want to access the sheet without having to save the file.
My Code so far:
public List<ApplicantEngExamBO> receiveAndSaveApplicantData(string database64, int exam_ID)
{
//converting file to byte[]
byte[] byteArray = Convert.FromBase64String(database64);
using (MemoryStream memStream = new MemoryStream(byteArray,0,byteArray.Length))
{
ExcelPackage package = new ExcelPackage(memStream);
package.Load(memStream);
//Just testing if it got any correct data
//It is not working
byte[] data = package.GetAsByteArray("ID");
var res = new List<ApplicantEngExamBO>();
foreach (var d in data)
{
res.Add(new ApplicantEngExamBO { studID = (int)d });
}
//return package;
return res;
}
}
How can we read the contents of the sheet without saving it, what to do next to get the data ? Other columns include "email".

OutOfMemory exception when trying to download multiple files as a Zip file using Ionic.Zip dll

This is my working code that I used to download multiple files as a zip file using Ionic.Zip dll. File contents is stored in a SQL database. This program works if I try to download 1-2 files at a time, but throws an OutOfMemory exception if I try to download multiple files as some of the files may very large.
Exception occurs when it's trying to write in to outputStream.
How can I improve this code to download multiple files or is there a better way to download multiple files one by one rather than zipping them to a one large file?
Code:
public ActionResult DownloadMultipleFiles()
{
string connectionString = "MY DB CONNECTIOBN STRING";
List<Document> documents = new List<Document>();
var query = "MY LIST OF FILES - FILE METADA DATA LIKE FILEID, FILENAME";
documents = query.Query<Document>(connectionString1).ToList();
List<Document> DOCS = documents.GetRange(0, 50); // 50 FILES
Response.Clear();
var outputStream = new MemoryStream();
using (var zip = new ZipFile())
{
foreach (var doc in DOCS)
{
Stream stream = new MemoryStream();
byte[] content = GetFileContent(doc.FileContentId); // This method returns file content
stream.Write(content, 0, content.Length);
zip.UseZip64WhenSaving = Zip64Option.AsNecessary // edited
zip.AddEntry(doc.FileName, content);
}
zip.Save(outputStream);
}
return File(outputStream, "application/zip", "allFiles.zip");
}
Download the files to disc instead of to memory, then use Ionic to zip them from disc. This means you don't need to have all the files in memory at once.

Create an Excel file on server and send to a browser

I'm using EPPlus to create an excel file on the server. The problem is that I wan't the file to be saved on the clients harddrive and when I the application up on a server I believe this will save the file on the server harddrive.
Is it possible to send this file back to the client/browser some how?
public void CreateAnnuityExcelSheet(List<Calculation> cList, FormCollection form, int DTCyear)
{
List<Calculation> newList = new List<Calculation>();
newList.Add(cList.First()); //Getting the values for the first row
var StartValue = newList[0].StartValue;
var radio = form["advanceOrArrears"];
string fileName = newList[0].CalculationName;
string path = #"C:\ExcelFiles\" + fileName + ".xlsx"; //Path for the file
FileInfo info = new FileInfo(path);
info.Directory.Create(); //If C:\ExcelFiles does not exist, create it
if (!info.Exists)
{
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(fileName);
//Styles for the sheet
package.Save();
}
}
}
The easiest way would be to send the bytes as File to browser. If your library for creating Excel files allows you to save to stream (like for example ClosedXML does) then you can do in your MVC action
var stream = new MemoryStream();
workbook.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "file.xlsx");
If you can't save it to memory stream then save it to server's disc and then you can just pass file path and content type to return File().
I've used a httphandler for sending the byte file object to the browser.
This link should help, Generating a file, then launching a secure download
So save the file on the server then transmit it to the user in your controller:
return new FilePathResult(myFilePath,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Read inside .DAT file using C#

I have .DAT from SharePoint, to recover some of the data I need to read the .DAT file using C#.
Some of the options are
StreamReader objInput = new StreamReader(filename, System.Text.Encoding.Default);
string contents = objInput.ReadToEnd().Trim();
string[] split = System.Text.RegularExpressions.Regex.Split(contents, "\\s+", RegexOptions.None);
foreach (string s in split)
{
Console.WriteLine(s);
}
or
//ObjectToSerialize objectToSerialize;
//Stream stream = File.Open(filename, FileMode.Open);
//BinaryFormatter bFormatter = new BinaryFormatter();
//objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
//stream.Close();
.../
The problem is the DAT file may contain XMl files, Doc files, or PPT or others. I just want list all the data and files inside the .DAT file.
Is there is any way I can do this is C#?
You can read .dat file using c#, but it depends on the structure of data how you have inside the .dat file
take a look at this link
How-read-data-from-DAT-file-using-C
how-can-i-read-data-from-dat-files

Categories