I want to export a .NET datatable to csv using FileHelpers.
The CommonEngine.DataTableToCsv doesn't cover my needs as it only writes to a file, I need it to be in memory.
I found a post which was using but the accepted answer CommonEngine.DataTableToCsv
DelimitedClassBuilder cb = new DelimitedClassBuilder("DataRow", ",", table);
Type t = cb.CreateRecordClass();
DelimitedFileEngine engine = new DelimitedFileEngine(t);
Can help would be awesome.
Thanks
Related
Just wondering if there's a way to mimic the "Format as Table" Excel function in C# for .csv files.
Context:
The WPF .NET Framework program I've created generates a 8x19 or 7x19 grid of data. The data collected is always different. My program can export this data into a CSV file. This is what it looks like when exported:
My customer is wanting the data in the CSV file to already be formatted into a table like so:
Is there a way to format it as a table after the data has been exported (besides manually doing it in Excel)?
Look into ClosedXML. Here is the documentation for your use case
It's published under MIT license.
Something like this should do the trick:
var wb = new XLWorkbook();
var ws = wb.AddWorksheet("Sheet1");
var range = ws.Range(1, 1, 50, 5);
var table = range.CreateTable();
table.Theme = XLTableTheme.TableStyleLight12;
I need to export Postgres DB (having around 20 tables) to excel using C#. I need to implement some logic on the data from DB and then need to export it. Any idea of how to export all data using c#?
using Npgsql;
using OfficeOpenXml; // Nuget EPPlus
using System.IO;
EPPlus has a one-step method to export a data table into a spreadsheet, so if you leveraged this, you should be able to loop through your queries and export each one to a unique sheet.
Something like this (untested but should be 99% there) should do the trick:
FileInfo fi = new FileInfo("foo.xlsx");
ExcelPackage excel = new ExcelPackage(fi);
int sheet = 1;
foreach (string sql in sqlQueries)
{
DataTable dt = new DataTable();
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
da.Fill(dt);
ExcelWorksheet ws = excel.Workbook.Worksheets.Add(string.Format("Sheet{0}", sheet++));
ws.Cells["A1"].LoadFromDataTable(dt, true);
}
excel.Save();
Of course, I'd recommend some refinements to deal with datatypes, formatting and the like, but this is the basic construct.
Also, of course, use the IDisposable using liberally.
The problem can be divided into two sub problems
Getting Data into c# from postgres.
pushing that data into excel.
Now solving a problem at a time
Here is a good article on working with postgres using c#
once you have you data in c# you can use any one of many libraries available for working with Excel using c#
One of them is NPOI
Here is one with example
Happy Coding.!!!
I need to read an EXCEL binary file (xls) in C#.
Basically its working, but i have problems with wrongly encoded characters (german umlauts for example).
Is there some way to specify an encoding? Does Excel files have something like an encoding at all?
The string in the Excel File is
Lydia Hömmerl
When reading with Jet or EDR i get:
Lydia HŠmmerl
I have tried OleDb and the Excel Data Reader project.
Here is the code i use to open and read the file:
var connectionString =
string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0};
Extended Properties=\"Excel 8.0;HDR=no\";", filePath);
var adapter = new OleDbDataAdapter(
"SELECT * FROM [Webshop orders$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "Orders");
var data = ds.Tables["Orders"].AsEnumerable();
foreach (var row in data)
{
var str = Convert.ToString(row[0]);
Unicode with C#
There are still many people who don't understand the difference between binary and text, or know what a character encoding is, etc. It is for these people that this page has been written. It mentions a few advanced topics, but only to make the reader aware of their existence, rather than to give much guidance on the topic.
Is there a performant way to load very big CSV-files (which have size of several gigabytes) into an SQL-Server 2008 database with .NET?
I would combine this CSV reader with SqlBulkCopy; i.e.
using (var file = new StreamReader(path))
using (var csv = new CsvReader(file, true)) // true = has header row
using (var bcp = new SqlBulkCopy(connection)) {
bcp.DestinationTableName = "TableName";
bcp.WriteToServer(csv);
}
This uses the bulk-copy API to do the inserts, while using a fully-managed (and fast) IDataReader implementation (crucially, which streams the data, rather than loading it all at once).
Look into using the SQLBulkCopy class.
Use SqlBulkCopy
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
I need a way to read a Excel file from a stream. It doesn't seem to work with the ADO.NET way of doing things.
The scenario is that a user uploads a file through a FileUpload and i need to read some values from the file and import to a database.
For several reasons I can't save the file to disk, and there is no reason to do so either.
So, anyone know of a way to read a Excel file from a FileUpload stream?
It seems i found a soultion to the problem myself.
http://www.codeplex.com/ExcelDataReader
This library seems to work nicely and it takes a stream to read the excel file.
ExcelDataReader reader = new ExcelDataReader(ExcelFileUpload.PostedFile.InputStream);
This can be done easily with EPPlus.
//the excel sheet as byte array (as example from a FileUpload Control)
byte[] bin = FileUpload1.FileBytes;
//gen the byte array into the memorystream
using (MemoryStream ms = new MemoryStream(bin))
using (ExcelPackage package = new ExcelPackage(ms))
{
//get the first sheet from the excel file
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
//loop all rows in the sheet
for (int i = sheet.Dimension.Start.Row; i <= sheet.Dimension.End.Row; i++)
{
//loop all columns in a row
for (int j = sheet.Dimension.Start.Column; j <= sheet.Dimension.End.Column; j++)
{
//do something with the current cell value
string currentCellValue = sheet.Cells[i, j].Value.ToString();
}
}
}
SpreadsheetGear can do it:
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(stream);
You can try it for yourself with the free evaluation.
Disclaimer: I own SpreadsheetGear LLC
Infragistics has an excel component that can read an excel file from a stream.
I'm using it in a project here and it works well.
Also the open source myXls component could easily be modified to support this. The XlsDocument contstructor only supports loading from a file given by a file name, but it works by creating a FileStream and then reading the Stream, so changing it to support loading from streams should be trivial.
Edit:
I see that you found a solution but I just wanted to note that I updated the source code for the component so that it now can read an excel file directly from a stream. :-)
I use ClosedXML nuget package to read excel content from stream. It has a constructor overload in XLWorkbook class which takes stream pointing to an excel file (aka workbook).
imported namespace at the top of your code file:
using ClosedXML.Excel;
Source code:
var stream = /*obtain the stream from your source*/;
if (stream.Length != 0)
{
//handle the stream here
using (XLWorkbook excelWorkbook = new XLWorkbook(stream))
{
var name = excelWorkbook.Worksheet(1).Name;
//do more things whatever you like as you now have a handle to the entire workbook.
var firstRow = excelWorkbook.Worksheet(1).Row(1);
}
}