I'm trying to find a simple way of writing an excel file in c#, but everything that I've found on thank you for your help.
You have two options available to you
The First is to use Interop Assemblies here is a link to some sample code on how to do that Write Data to Excel using C#
The Second option is to use OLEDB. There is some information on Stack Overflow on that here
Use epplus as mentioned above,It makes it really simple. This is the code for a spread sheet i created with it today.
using (ExcelPackage pck = new ExcelPackage())
{
//Give the worksheet a name
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Inventory as of " + DateTime.Now.ToString("MM/dd/yyyy"));
//dt is a datable that i am turning into an excel document
ws.Cells["A1"].LoadFromDataTable(dt, true);
//Format the header columns(Color,Pattern,etc.)
using (ExcelRange rng = ws.Cells["A1:AA1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//End Format the header columns
//Give the file details(ie. filename, etc.)
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Inventory Report " + DateTime.Now.ToString("MM/dd/yyyy") + ".xlsx");
//Write the file
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
pck.Save();
}
what you would need is epplus, this will help you to create 2007+ excel file
not compatible with 2003 and under
There is no really easy way depending of the version of excel file you want to write. If you want to go for xls you won't have much options than using Excel interop which would also have the dependency to have Excel installed.
The newer version offers some more options as it is just XML in the background. You can choose yourself how to create it, either yourself, some libraries or again Interop.
If you just want to display a table without any styling, there was (afair) a way to write csv file and excel can open it quite well (depending on the data types you want to use in it).
Related
I have a project where my goal is to produce an .xlsm Excel spreadsheet using .NET and the EEPlus 5.8.14 Excel Spreadsheet library. I can do this using EEPlus's documented techniques, (though some of these I cannot get to work). As I was working on this, I realized that what my code needed to do was relatively small, and it made sense to use an existing .xlsm file as a template and just make changes to what I needed to change using EEPlus.
So now I am including the .xlsm file as a resource compiled into the assembly. This works great, and I can read the file from the resources and produce it from my controller. But once read, this data inside EPPlus seems to be read-only. So while this produces an Excel file:
public ActionResult ExcelFile(){
const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Byte[] bytes = Properties.Resources.AssetsEntry;
string fstem = Path.GetRandomFileName();
int unique = 0;
string filePath = String.Format("{0}#AutoGen_{1}_{2}.{3}", Path.GetTempPath(), fstem, ++unique, "xlsm");
var outStream = System.IO.File.OpenWrite(filePath);
var writer = new BinaryWriter(outStream);
writer.Write(bytes);
outStream.Close();
ExcelPackage excelPackage = new ExcelPackage(filePath);
var sheet = excelPackage.Workbook.Worksheets[1];
//place where I might want to change data
//sheet.Cells["B3"].Value = "testing";
var excelData = excelPackage.GetAsByteArray();
var fileName = "ExcelFile.xlsm";
return File(excelData, ContentType, fileName);
}
If I try to uncomment out the second commented-out line, that code fails to change the resulting Excel spreadsheet (though there is no error). How do I go about reading in an Excel spreadsheet and making changes using EEPlus?
UPDATE: I can add new worksheets to an uploaded spreadsheet, and I can alter those added sheets. But I cannot alter data on uploaded worksheets. Fortunately, for this particular project, that is acceptable. But it would be frustrating if I wanted to be able to set up a worksheet in Excel and then populate it programmatically.
I currently have an option in my app to export to Excel. It saves the data to a file in disk.
I would like to open Excel instead and show the data. Do any of you know if this is possible and how to accomplish it?
I guess I can just open the file I'm already saving to disk, but it would be just better to not save a file to disk at all.
I am assuming you are using Interop. Just set the Application to Visible.
excelApp.Visible = true;
where
InteropExcel.Application excelApp;
Just remember to still release all the COM references so that your application does not also hold a handle to Excel. That may cause your Excel file to be read-only.
How are you currently creating your file?
If you are using the Excel engine or POI (or what ever thier abbreviation is) to create an XLS / XLSX it would just be a case of not saving the workbook and making the instance visible (as per above)?
If you are not dependant on or do not want to be dependant on Excel (i.e. using 3rd party libraries like Syncfusion to create the file) or just outputting your data in an excel readable format like CSV, then I guess you're stuck with a file-based operation...
As for a temp file being easier than an unsaved one... the data needs to be created in either instance, either simple CSV or a coded population of Excel cells, so I don't quite see what is meant by that.
Refer Below code to open excel without saving
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=DateTime.Now + ".xls");
System.Web.HttpContext.Current.Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache); // If you want the option to open the Excel file without saving than
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Gridview1.RenderControl(htmlWrite);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
System.Web.HttpContext.Current.Response.Write(style);
System.Web.HttpContext.Current.Response.Output.Write(stringWrite.ToString());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
i have two question to asp.net and listview. I have a webapplication with a listview. this listview fill with data from users by active directory. the listview show only searched user.
Question 1:
I want to import this ListView in a Excel file. How I can do this? Must I use CSV for this?
Question 2:
I want print out this listview. How I can do this or is it better if I make a excel file and the user print this file :/
I need tipps ans good links :)
thanks <3
1 - Please check these links about how to export listview to excel file :
http://forums.asp.net/p/1245474/2583840.aspx
http://www.c-sharpcorner.com/uploadfile/vasanthks/export-gridviewlistview-to-excel-with-color-formatting/
http://www.dotnetlogix.com/article/aspnet/56/How-to-export-listview-in-excel-in-asp.net.html
2 - For Printing you can do Reporting :)
Good luck!
If you only want to print out the list, then you can print from the web-interface. Create a page with the content you want to print and the follow these instructions:
http://www.w3schools.com/jsref/met_win_print.asp
Question 1: No, you don't need to use CSV. You could use EPPlus for exporting to Excel. It does an amazing job and there's not much you can't do with it in terms of exporting.
Question 2: I'd use the above, but it depends on the requirements of the person who's printing the file. You could just dump a plain list, but Excel would be better IMHO.
Just to complete this... some pseudo code for you to generate a simple spreadsheet...
using OfficeOpenXml;
using (ExcelPackage outPackage = new ExcelPackage(YOUR_DESTINATION_FILENAME))
{
// Add new worksheet
ExcelWorksheet destWorkSheet = outPackage.Workbook.Worksheets.Add("Spreadsheet name");
// Draw header
destWorkSheet.Cells[1, 1].Value = "Header 1";
destWorkSheet.Cells[1, 2].Value = "Header 2";
// Loop through your data and add rows
for (int i = 0; i < YOURDATA.Count; i++)
{
destWorkSheet.Cells[i+2, 1].Value = YOUR_DATA_1;
destWorkSheet.Cells[i+2, 2].Value = YOUR_DATA_2;
}
// Save spreadsheet
outPackage.Save();
}
Hope this helps,
{
Response.ClearContent();
Response.Buffer = true;
string fileName="filname.xlsm";Response.AddHeader("content-disposition", string.Format("attachment;filename={0}",fileName));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ListView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
well for printing and saving to Excel , PDF, Word and printing purposes i prefer using RDLC as its easier to maintain it. i don't have good experience using this third party office controls and dlls.
Wondering what is a good library I can use with VS2005 to export data to a excel file. The file has some formatting like background colors and colspans.
Thanks
Here is some code that uses a trick to output HTML to an Excel file. I have found that you can trick excel into opening an HTML by setting the content type of the output to "application/excel".
In the code below secresults is an HTML div like so:
<div id="secresults" runat="server" visible="false" class="secresults">
Content or data here.
</div>
In code behind:
Response.ClearContent();
string filename = "Output" + istartDate.ToShortDateString() + ".xls";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
secresults.RenderControl(htw);
Response.Write(sw.toString());
Response.End();
I have found that you can use some html formatting in excel. To test which formatting you can use you can create an html file and rename it to a .xls file, then open it with excel. You can get a pretty good idea about what HTML Excel will read.
I would recommend taking the class from the following website, and adapting it to your needs.
Mikes Knowledge Base - ExportToExcel
By default, this class takes a DataSet, DataTable or List<>, and exports it into a genuine Excel 2007 .xlsx file, using the OpenXML libraries (also provided).
It doesn't currently attempt to add any formating to the Excel cells (DataTables only store values, not formating, colors, horizontal alignment, etc !) but it should be a good place to start from.
All source code is provided, free of charge, so you can adapt it as required.
Good luck !
I have used this library in the past, but I normally just spit out a CSV file.
C# class library for exporting data to CSV/Excel file
If you have predefined layout of the document, Templater will probably fit your description.
Take a look at the example on how to use it.
I've used this codeplex project (Excel Package). One technique is to start with a formatted template, then modify the template. That is much easier than applying a lot of styling commands starting with an empty spreadsheet.
I want to read excel file but in this way is too slow. What pattern should I use to read excel file faster. Should I try csv ?
I am using the following code:
ApplicationClass excelApp = excelApp = new ApplicationClass();
Workbook myWorkBook = excelApp.Workbooks.Open(#"C:\Users\OWNER\Desktop\Employees.xlsx");
Worksheet mySheet = (Worksheet)myWorkBook.Sheets["Sheet1"];
for (int row = 1; row <= mySheet.UsedRange.Rows.Count; row++)
{
for (int col = 1; col <= mySheet.UsedRange.Columns.Count; col++)
{
Range dataRange = (Range)mySheet.Cells[row, col];
Console.Write(String.Format(dataRange.Value2.ToString() + " "));
}
Console.WriteLine();
}
excelApp.Quit();
The reason your program is slow is because you are using Excel to open your Excel files. Whenever you are doing anything with the file you have to do a COM+ interop, which is extremely slow, as you have to pass memory across two different processes.
Microsoft has dropped support for reading .xlsx files using Excel interop. They released the OpenXML library specifically for this reason.
I suggest you use a wrapper library for using OpenXML, since the API is pretty hairy. You can check out this SO for how to use it correctly.
open xml reading from excel file
You're accessing Excel file through excel interop. By doing reads cell by cell you're doing a lot of P/Invoke's which is not very performant.
You can read data in ranges, not cell by cell. This loads the data into memory and you could iterate it much faster. (Eg. try to load column by column.)
BTW: You could use some library instead like http://epplus.codeplex.com which reads excel files directly.
Excel Data Reader
Lightweight and very fast if reading is your only concern.