Is it possible to add a custom header to the Excel while exporting a DataSet to Excel in ASP.NET?
I have one requirement like this. I can export the DataSet to the Excel successfully. But I can't add the custom header. Please help me if anybody have the solution. Thanks in advance.
IF you are using Response.Write to Export the Excel.
You can use the following code with minimal effort and the Header can be customized as you want, just like HTML headers.
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
dgrExport.DataSource = dtExport;
dgrExport.DataBind();
dgrExport.RenderControl(htmlWrite);
string headerTable = #"<Table><tr><td>Report Header</td></tr><tr><td><img src=""D:\\Folder\\Report Header.jpg"" \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Mac, Are you looking for the same?
I got a little treat for you. This is a full blown Excel handler I wrote after lots of studying of Excel Interop. Look at the line "dataGridView1 = YOUR_DATATABLE_HERE;" I know it says dataGridView, it's DataTable, just FYI. Feed it that and you are golden. Of course you would need to convert a dataset to DataTable, but that's another question. Simply put, you can copy and paste this code, and all you have to change is the YOUR_DATATABLE_HERE variable with an actual DataTable and that thing will do the rest. There are lots of commented out sections. Uncomment them as needed. They should be self explanatory. Oh FYI... if your PageSetup does not work properly, that's a headache. It could be anything from you need to add a printer to some really fancy stuff, however it's host computer dependant, not code dependant. If that ends up crashing you, please comment out that section.
Notice the "#region Column Headers" part of the code. Here you can change the headers. In my code I simply pull them from the table but you can customize them. Let me know if you need help with that portion, but again, it should be self explanatory. I know this is a huge chunk of code, but the nice thing is, it's practically ready to go as-is. All you have to do is throw it in your project, feed it a DataTable, maybe add some resources (i.e. anything that's underlined red, just right click it and choose resolve), and you should be set to go for Excel anything. Good luck to you!
#region Excel Interop Object Private Methods
private void ExportToExcel()
{
#region Initialize Variables
DataTable dataGridView1 = new DataTable();
//Load source
dataGridView1 = YOUR_DATATABLE_HERE;
//Declare Excel Interop variables
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//Initialize variables
xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
#endregion
#region Title
//Add a title
xlWorkSheet.Cells[1, 1] = "Your title here";
//Span the title across columns A through H
Microsoft.Office.Interop.Excel.Range titleRange = xlApp.get_Range(xlWorkSheet.Cells[1, "A"], xlWorkSheet.Cells[1, "F"]);
titleRange.Merge(Type.Missing);
//Center the title horizontally then vertically at the above defined range
titleRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
titleRange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
//Increase the font-size of the title
titleRange.Font.Size = 16;
//Make the title bold
titleRange.Font.Bold = true;
//Give the title background color
titleRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
//Set the title row height
titleRange.RowHeight = 50;
#endregion
#region Column Headers
//Populate headers, assume row[0] contains the title and row[1] contains all the headers
int iCol = 0;
foreach (DataColumn c in dataGridView1.Columns)
{
iCol++;
xlWorkSheet.Cells[2, iCol] = dgResults.Columns[iCol - 1].HeaderText;
}
//Populate rest of the data. Start at row[2] since row[1] contains title and row[0] contains headers
int iRow = 2; //We start at row 2
foreach (DataRow r in dataGridView1.Rows)
{
iRow++;
iCol = 0;
foreach (DataColumn c in dataGridView1.Columns)
{
iCol++;
xlWorkSheet.Cells[iRow, iCol] = r[c.ColumnName];
}
}
//Select the header row (row 2 aka row[1])
Microsoft.Office.Interop.Excel.Range headerRange = xlApp.get_Range(xlWorkSheet.Cells[2, "A"], xlWorkSheet.Cells[2, "F"]);
//Set the header row fonts bold
headerRange.Font.Bold = true;
//Center the header row horizontally
headerRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//Put a border around the header row
headerRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous,
Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium,
Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,
Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic);
//Give the header row background color
headerRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.MediumPurple);
#endregion
#region Page Setup
//Set page orientation to landscape
xlWorkSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
//Set margins
xlWorkSheet.PageSetup.TopMargin = 0;
xlWorkSheet.PageSetup.RightMargin = 0;
xlWorkSheet.PageSetup.BottomMargin = 30;
xlWorkSheet.PageSetup.LeftMargin = 0;
//Set Header and Footer (see code list below)
//&P - the current page number.
//&N - the total number of pages.
//&B - use a bold font*.
//&I - use an italic font*.
//&U - use an underline font*.
//&& - the '&' character.
//&D - the current date.
//&T - the current time.
//&F - workbook name.
//&A - worksheet name.
//&"FontName" - use the specified font name*.
//&N - use the specified font size*.
//EXAMPLE: xlWorkSheet.PageSetup.RightFooter = "&F"
xlWorkSheet.PageSetup.RightHeader = "";
xlWorkSheet.PageSetup.CenterHeader = "";
xlWorkSheet.PageSetup.LeftHeader = "";
xlWorkSheet.PageSetup.RightFooter = "";
xlWorkSheet.PageSetup.CenterFooter = "Page &P of &N";
xlWorkSheet.PageSetup.LeftFooter = "";
//Set gridlines
xlWorkBook.Windows[1].DisplayGridlines = true;
xlWorkSheet.PageSetup.PrintGridlines = true;
#endregion
#region Worksheet Style
/*
//Color every other column but skip top two
Microsoft.Office.Interop.Excel.Range workSheetMinusHeader = xlApp.get_Range("A1", "F1");
Microsoft.Office.Interop.Excel.FormatCondition format =
(Microsoft.Office.Interop.Excel.FormatCondition)workSheetMinusHeader.EntireColumn.FormatConditions.Add(
Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlEqual,
"=IF(ROW()<3,,MOD(ROW(),2)=0)");
format.Interior.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbWhiteSmoke;
//Put a border around the entire work sheet
workSheetMinusHeader.EntireColumn.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous,
Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium,
Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic,
Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic);
*/
#endregion
#region Specific Width, Height, Wrappings, and Format Types
//Set the font size and text wrap of columns for the entire worksheet
string[] strColumns = new string[] { "A", "B", "C", "D", "E", "F" };
foreach (string s in strColumns)
{
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns[s, Type.Missing]).Font.Size = 12;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns[s, Type.Missing]).WrapText = true;
}
//Set Width of individual columns
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["A", Type.Missing]).ColumnWidth = 7.00;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["B", Type.Missing]).ColumnWidth = 18.00;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["C", Type.Missing]).ColumnWidth = 18.00;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["D", Type.Missing]).ColumnWidth = 30.00;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["E", Type.Missing]).ColumnWidth = 40.00;
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Columns["F", Type.Missing]).ColumnWidth = 15.00;
//Select everything except title row (first row) and set row height for the selected rows
//xlWorkSheet.Range["a2", xlWorkSheet.Range["a2"].End[Microsoft.Office.Interop.Excel.XlDirection.xlDown].End[Microsoft.Office.Interop.Excel.XlDirection.xlToRight]].RowHeight = 45;
//Format date columns
//string[] dateColumns = new string[] { "N", "O", "P", "Q" };
string[] dateColumns = new string[] { };
foreach (string thisColumn in dateColumns)
{
Microsoft.Office.Interop.Excel.Range rg = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, thisColumn];
rg.EntireColumn.NumberFormat = "MM/DD/YY";
}
//Format ID column and prevent long numbers from showing up as scientific notation
//Microsoft.Office.Interop.Excel.Range idRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, "C"];
//idRange.EntireColumn.NumberFormat = "#";
//Format Social Security Numbers so that Excel does not drop the leading zeros
//Microsoft.Office.Interop.Excel.Range idRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, "C"];
//idRange.EntireColumn.NumberFormat = "000000000";
#endregion
#region Save & Quit
//Save and quit, use SaveCopyAs since SaveAs does not always work
string fileName = Server.MapPath("~/YourFileNameHere.xls");
xlApp.DisplayAlerts = false; //Supress overwrite request
xlWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
//Release objects
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
//Give the user the option to save the copy of the file anywhere they desire
String FilePath = Server.MapPath("~/YourFileNameHere.xls");
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=YourFileNameHere-" + DateTime.Now.ToShortDateString() + ".xls;");
response.TransmitFile(FilePath);
response.Flush();
response.Close();
//Delete the temporary file
DeleteFile(fileName);
#endregion
}
private void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch (Exception ex)
{
//Could not delete the file, wait and try again
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(fileName);
}
catch
{
//Could not delete the file still
}
}
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Response.Write("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
#endregion
As you are using dataset, you can change the value in the first row of the dataset if you are using that to be your column names and then export the dataset to excel:
ds.Tables[0].Rows[0][0] = "New Column Name"; // change the column value
Related
I'm trying to create a excel from a datagrid with wpf, however when I format a column to just text it still converts some columns to what I presume to be a date conversion.
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
This is how the conversion of the column is set, but this results in Excel still formatting some fields to a date-ish value... If you look at the column foutcode you'll see what I mean.
results in:
I think what happens is that it automatically recognizes the value and sees if it fits a date format while I'm telling it to handle as just regular text! So does anyone have any idea on how to get rid of that? because the data is unusable because of this small error. Maybe use a more specific format than just text? however I can't seem to figure out how.
Also Convert a lot of rows into excel takes some quite a bit of time (4-5s for 1000 rows). Is there a way to make it go faster? All help is really appreciated.
public void ExportToExcel(List<Fouten> data)
{
try
{
if (data.Count > 0)
{
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = "Data rapport";
// If the User Clicks the Save Button then the Module gets executed otherwise it skips the scope
if ((bool)saveFileDialog1.ShowDialog())
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rowCount = 1;
xlWorkSheet.Cells[rowCount, 1] = "Datum";
xlWorkSheet.Cells[rowCount, 2] = "Tijd";
xlWorkSheet.Cells[rowCount, 3] = "Foutcode";
xlWorkSheet.Cells[rowCount, 4] = "Omschrijving";
xlWorkSheet.Cells[rowCount, 5] = "Module";
xlWorkSheet.Cells[rowCount, 6] = "TreinId";
rowCount++;
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 2];
rg.EntireColumn.NumberFormat = "hh:mm:ss.000";
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
foreach (Fouten item in data)
{
string[] moduleNaam = item.Module.Split('_');
xlWorkSheet.Cells[rowCount, 1] = item.Datum;
xlWorkSheet.Cells[rowCount, 2] = item.Time.ToString();
xlWorkSheet.Cells[rowCount, 3] = item.FoutCode;
xlWorkSheet.Cells[rowCount, 4] = item.Omschrijving;
xlWorkSheet.Cells[rowCount, 5] = moduleNaam[0].ToUpper();
xlWorkSheet.Cells[rowCount, 6] = item.TreinId;
rowCount++;
}
xlWorkSheet.Columns.AutoFit();
// If the file name is not an empty string open it for saving.
if (!String.IsNullOrEmpty(saveFileDialog1.FileName.ToString()) && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName.ToString()))
{
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel File Exported Successfully", "Export Engine");
}
}
}
}
else
{
MessageBox.Show("Nothing to Export", "Export Engine");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The Range.NumberFormat property for Text is an 'at' symbol (e.g. capital 2 or #), not the word Text.
rg1.EntireColumn.NumberFormat = "#";
More at Number Format Codes.
I have a small web application that creates two datatables from a jquery datepicker. I am able to export those datatables to excel of course if they are on the same page.
I've changed my application to render the datatables on new webforms.
Here is my code to export to excel:
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);
GridView2.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView2.HeaderRow.Cells)
{
cell.BackColor = GridView2.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView2.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView2.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView2.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView2.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
Here is where I am having trouble:
this.BindGrid1(TextDateFrom.Text, TextDateTo.Text);
Of course my BindGrid1() is an another form. To call my datatables in my new forms I created a session.
If I have the code on the web form where the data tables are:
DataTable dt = (DataTable)Session["GridData"];
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
I'm not sure exactly how to call that this. to export all pages. Should I have created a global variable that takes the String values from the BindGrid1 method to then use on the new page?
Pertinent to your task, the data export from DataTable dt to Excel can be achieved using the following procedure, which utilizes Microsoft.Office.Interop.Excel object library:
/// <summary>
/// export DataTable to Excel (C#)
/// </summary>
internal static void Export2Excel(DataTable dataTable)
{
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application _appExcel = null;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
try
{
// excel app object
_appExcel = new Microsoft.Office.Interop.Excel.Application();
// excel workbook object added to app
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
_excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
// column names row (range obj)
Microsoft.Office.Interop.Excel.Range _columnsNameRange;
_columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);
// column names array to be assigned to _columnNameRange
string[] _arrColumnNames = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
// array of column names
_arrColumnNames[i] = dataTable.Columns[i].ColumnName;
}
// assign array to column headers range, make 'em bold
_columnsNameRange.set_Value(misValue, _arrColumnNames);
_columnsNameRange.Font.Bold = true;
// populate data content row by row
for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
{
_excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
dataTable.Rows[Idx].ItemArray;
}
// Autofit all Columns in the range
_columnsNameRange.Columns.EntireColumn.AutoFit();
}
catch { throw; }
}
just pass dt as an argument.
Hope this may help.
I want to delete a Chart from an Excel file.
The Excel file is an automatically generated historyfile with a chart, the problem is, that every time I renew the history, it makes a new chart, but the old one must be deleted...
This is my code:
Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(path);
ExcelApp.Visible = true;
Excel.Worksheet Sheet = (Excel.Worksheet)ExcelWorkBook.Worksheets.get_Item(1);
Excel.Range range = Sheet.UsedRange;
int i = 2;
while (Convert.ToString((range.Cells[i, 1] as Excel.Range).Value2) != null)
{
i++;
}
Excel.Range oRange;
Excel._Chart oChart;
Excel.Series oSeries;
oChart = (Excel._Chart)ExcelWorkBook.Charts.Add(Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oRange = Sheet.get_Range("A2:H" + i).get_Resize(Missing.Value, 8);
oChart.ChartWizard(oRange, Excel.XlChartType.xlLineStacked, Missing.Value,
Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,"Chart01");
oSeries = (Excel.Series)oChart.SeriesCollection(1);
oSeries.XValues = Sheet.get_Range("A2", "A" + i);
oChart.Location(Excel.XlChartLocation.xlLocationAsObject, Sheet.Name);
Now I need to delete the existing Chart before that code.
Something like
Excel._Chart asdf = Sheet.ChartObjects("Chart01").Chart;
if (asdf != null)
{
asdf.Delete();
}
This doesn't find a chart with name "Übersicht" but there is a chart with title "Übersicht"
EDIT:
The Problem now is that it can't delete the Chart: Exception from HRESULT: 0x800A03EC
In Excel make sure that the Chart actually exists with the name.
You can rename a chart using
Sheets("Sheet1").ChartObjects(1).Name = "Chart01"
then when you click on the chart in the spreadsheet view you can see that it actually renamed
On the C# side I would suggest a minimal example like this
bool deleted = false;
try
{
ChartObject myChart = ws.ChartObjects("Chart01");
myChart.Delete();
deleted = true;
}
catch
{
MessageBox.Show("Chart with this name could not be found");
//throw new Exception("Chart with this name could not be found");
}
finally
{
MessageBox.Show("the chart was " + (deleted ? "deleted" : "not deleted"));
}
Try to rename the chart name to plain English like: 'Chart01'.
The issue might be due to Unicode support.
This is my code to generate Excel using COM interop.
public static void ExportDataTableToExcel(DataTable dt, string filepath)
{
object missing = Type.Missing;
object misValue = System.Reflection.Missing.Value;
//create excel
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//add excel workbook
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Add();
//add worksheet to worlbook
Microsoft.Office.Interop.Excel.Worksheet ws = wb.Sheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//Set the header-row bold
ws.Range["A1", "A1"].EntireRow.Font.Bold = true;
//Adjust all columns
ws.Columns.AutoFit();
//spit top row
ws.Application.ActiveWindow.SplitRow = 1;
//freeze top row
ws.Application.ActiveWindow.FreezePanes = true;
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
ws.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
ws.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
wb.SaveAs(#"C:\ErangaExcelTest.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue,
misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue,
misValue, misValue, misValue, misValue);
wb.Close(missing, missing, missing);
excel.Quit();
}
This is the Excel which I get from this method.
I need a colourful table like this
What kind of modifications do I need to do have this kind of colourful Excel ?
You need to set the font color and the background color for each cell. You are already setting the font to bold by:
ws.Range["A1", "A1"].EntireRow.Font.Bold = true;
Now the Font object has more properties. To set the font color use the Range.Font.Color property. To set background color for a cell, see the Range.Interior property. Specifically you want to set Pattern to xlPatternSolid and then set some color with Color property of the Interior object.
In VBA you can specify fonts with their RGB values:
range.Font.Color = RGB(255, 0, 0)
will set the font color of the range to red.
To change borders, use the Range.Borders property. The link has an example code on how to use it.
I want to export data from Dataset or Data Table to Excel file in C# without using Gridview.
I would recommend EPPlus - this solution doesn't require COM nor interop dlls and is very fast. Perfectly suited for web scenarios.
http://epplus.codeplex.com/
http://nuget.org/packages/EPPlus
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
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);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
}
}
Get more ways : 9 Solutions to Export Data to Excel for ASP.NET
I have this code but for this you need to include Excel Com Component
Add reference of Microsoft.Office.Interop.Excel.dll in your project will do task for you.
using Excel = Microsoft.Office.Interop.Excel;
public static bool ExportDataTableToExcel(DataTable dt, string filepath)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
you can use
using Microsoft.Office.Interop.Excel;
to work with excel documents "native"...
Using C# to Create an Excel Document
http://www.codeproject.com/Articles/20228/Using-C-to-Create-an-Excel-Document
But most of the common report Generator/Designers can easily export to excel
also check for Reporting Services if you are using SQL SERVER
Just in case somebody else used the chosen solution and run into the "object does not contain a definition for get_Range" exception. I found the solution here: Worksheet get_Range throws exception. I hope this will save your time.