I have one Data table which is converting to the excel.for this i am using EPPlus dll. Here i am getting the generated excel file. but my problem is there are 2 columns are existing with rich text value. After Conversion the above column is always showing data with HTML tag. How I resolve this issue. Please help me. thanks in advance
My code is shown below
try
{
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
DataTable dtTemp = new DataTable();
if (ViewState["DTSource"] != null)
dtTemp = (DataTable)ViewState["DTSource"];
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
if (dtTemp != null && dtTemp.Rows.Count > 0)
{
ws.Cells["A1"].LoadFromDataTable(dtTemp, true);
using (ExcelRange rng = ws.Cells["A1:" + GetColumnName(dtTemp.Columns.Count) + "1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));
rng.Style.Font.Color.SetColor(Color.White);
}
for (int i = 0; i < dtTemp.Columns.Count; i++)
{
if (dtTemp.Columns[i].DataType.FullName.Contains("DateTime"))
{
ws.Cells[2, i + 1, dtTemp.Rows.Count + 1, i + 1].Style.Numberformat.Format = "MM/dd/yyyy";
ws.Column(i + 1).Width = 15;
}
using (ExcelRange col = ws.Cells[2, 1, 2 + dtTemp.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
using (ExcelRange col = ws.Cells[2, 4, 2 + dtTemp.Rows.Count, 4])
{
col.IsRichText = true;
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
}
Page.Response.Clear();
Page.Response.AddHeader("content-disposition", "attachment; filename=ExceptionTracker_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
Page.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Page.Response.BinaryWrite(pck.GetAsByteArray());
Page.Response.End();
}
}
else
{
string script = "window.frameElement.cancelPopUp(); return false;";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close Window", script, true);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
Shouldn't this part be somewhere else? Maybe after you have finished creating the file?
Page.Response.Clear();
Page.Response.AddHeader("content-disposition", "attachment; filename=ExceptionTracker_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
Page.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Page.Response.BinaryWrite(pck.GetAsByteArray());
Page.Response.End();
Related
First of all I know there are some answers to this error messsage, but nothing has helped, whether it is the removal of 0 indexing etc.
The part where I export the data from my SQL query to the DataTable is working and the data in my DataTable is correct, so that's not the problem.
The first part is my Excel and is where I check if there is an existing file or not and create a new file with the data. newsletter is my DataTable - I know its not a good name:
string path2 = "C:\\Users\\pandev\\newsletter.xls";
if (File.Exists(path2) == true)
{
Process[] pp = Process.GetProcessesByName("excel");
foreach (Process p in pp)
{
if (p.MainWindowTitle.Length == 0)
p.Kill();
}
File.Delete(path2);
}
using (FileStream sw = File.Create(path + "newsletter" + ".xls"))
{
var data = Encoding.Unicode.GetBytes("Artikelnummer" + "\t" + "Hersteller" + "\t" + "Beschreibung" + "\t" + "Nettopreis" + "\t" + "Bruttopreis" + "\t" + "Zustand" + "\t" + "P/N" + "\t" + "Kategorie I" + "\t" + "Kategorie II" + "\t" + "Kategorie III" + "\t" + "Shop-Link" + "\n");
sw.Write(data, 0, data.Length);
foreach (DataRow r in newsletter.Rows)
{
data = Encoding.Unicode.GetBytes(r["Artikelnummer"].ToString() + "\t" + r["Hersteller"].ToString() + "\t" + r["Bezeichnung"].ToString() + "\t" + r["Nettopreis"].ToString() + "\t" + r["Bruttopreis"].ToString() + "\t" + r["Zustand"].ToString() + "\t" + r["PN"].ToString() + "\t" + r["Kategorie I"].ToString() + "\t" + r["Kategorie II"].ToString() + "\t" + r["Kategorie III"].ToString() + "\t" + r["Link"].ToString() + "\n");
sw.Write(data, 0, data.Length);
}
}
Then I have this following code to make some Style changes in the Excel sheet:
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oWB = oXL.Workbooks.Open(path + "newsletter.xls");
Microsoft.Office.Interop.Excel.Worksheet oWS = oWB.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Range exrngKopf = (Microsoft.Office.Interop.Excel.Range)oWS.Rows[1].Cells[1, oWS.Columns.Count];
Microsoft.Office.Interop.Excel.Range allBZ = oWS.UsedRange;
allBZ.EntireColumn.AutoFit();
error += "T";
oXL.DisplayAlerts = false;
error += "T";
oWS.Name = "GEKKO Computer GmbH";
error += "T";
oWS.Cells.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone;
error += "T";
exrngKopf.EntireRow.Font.Bold = true;
error += "T";
oWB.Activate();
error += "T";
oWB.Application.ActiveWindow.SplitRow = 1;
error += "T";
oWB.Application.ActiveWindow.FreezePanes = true;
error += "T";
Microsoft.Office.Interop.Excel.Range Firstrow = (Microsoft.Office.Interop.Excel.Range)oWS.Rows[1];
error += "T";
error += "x";
if (oWS.AutoFilter != null)
oWS.AutoFilterMode = false;
oWS.ListObjects.AddEx(Microsoft.Office.Interop.Excel.XlListObjectSourceType.xlSrcRange, allBZ, Type.Missing, Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes, Type.Missing).Name = "WFTableStyle";
oWS.ListObjects.get_Item("WFTableStyle").TableStyle = null;
oWB.SaveAs(path + "newsletter.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oWB.Close(true, Missing.Value, Missing.Value);
oXL.Quit();
So normally thats working, but now I have the special case where there is a Hyperlink in the data:
How I want the Hyperlink to look in the Excel cell is:
And like this in the edit field of that cell:
To fix the hyperlink I've placed the following code within the previous code snippet - before the SaveAs Close and Quit part:
for (int i = 0; i < newsletter.Rows.Count; i++)
{
for (int j = 0; j < newsletter.Columns.Count; j++)
{
oWS.Cells[i + 1, j + 1] = newsletter.Rows[i][j].ToString();
}
}
It's working. Every time I execute that code it saves the data correct in the Excel sheet, but the following exception occurs HRESULT: 0x800A03EC.
Does anyone have an idea on how to fix that?
I also tried something like this but still receive the same error:
for (int Idx = 1; Idx < newsletter.Columns.Count; Idx++)
{
oWS.Range["A1"].Offset[0, Idx].Value = newsletter.Columns[Idx].ColumnName;
}
for (int Idx = 1; Idx < newsletter.Rows.Count; Idx++)
{ // <small>hey! I did not invent this line of code,
// I found it somewhere on CodeProject.</small>
// <small>It works to add the whole row at once, pretty cool huh?</small>
oWS.Range["A2"].Offset[Idx].Resize[1, newsletter.Columns.Count].Value =
newsletter.Rows[Idx].ItemArray;
}
Given the following definition for DataTable (name: dataTableNewsLetter):
DataTable dataTableNewsletter = new DataTable();
//add columns
//dataTableNewsletter.Columns.Add(new DataColumn() { Caption = "Artikelnummer", ColumnName = "Artikelnummer", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Artikelnummer", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Hersteller", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Beschreibung", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Nettopreis", DataType = System.Type.GetType("System.Decimal") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Bruttopreis", DataType = System.Type.GetType("System.Decimal") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Zustand", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "P/N", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Kategorie I", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Kategorie II", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Kategorie III", DataType = System.Type.GetType("System.String") });
dataTableNewsletter.Columns.Add(new DataColumn() { ColumnName = "Shop-Link", DataType = System.Type.GetType("System.String") });
//add data
DataRow row = dataTableNewsletter.NewRow();
row["Artikelnummer"] = "50018113"; //item number
row["Hersteller"] = "HP"; //manufacturer
row["Beschreibung"] = "HP DL38X Gen10 2 Drive NVMe Slim SAS Cable Kit - 871827-B21 NEU"; //description
row["Nettopreis"] = 195; //net price
row["Bruttopreis"] = 195; //gross price
row["Zustand"] = "New"; //condition
row["P/N"] = "869812-001"; //part number
row["Kategorie I"] = "Komponenten"; //category 1
row["Kategorie II"] = "Kabel-Adapter"; //category 2
row["Kategorie III"] = "NVMe-Kabel"; //category 3
row["Shop-Link"] = "https://www.gekko-computer.de/Komponenten/Kabel-Adapter/NVMe-Kabel/HP-DL38X-Gen10-2-Drive-NVMe-Slim-SAS-Cable-Kit-871827-B21-NEU.html"; //URL
//add
dataTableNewsletter.Rows.Add(row);
//add new row
row = dataTableNewsletter.NewRow();
row["Artikelnummer"] = "50015171"; //item number
row["Hersteller"] = ""; //manufacturer
row["Beschreibung"] = "NetApp Ethernet Kabel CAT 6 2m - 112-00195 X6561-R6"; //description
row["Nettopreis"] = 38; //net price
row["Bruttopreis"] = 38; //gross price
row["Zustand"] = "Used"; //condition
row["P/N"] = "112-00195"; //part number
row["Kategorie I"] = "sonstiges"; //category 1
row["Kategorie II"] = "Kabel-Adapter"; //category 2
row["Kategorie III"] = "Ethernet-Kabel"; //category 3
row["Shop-Link"] = "https://www.gekko-computer.de/sonstiges/Kabel-Adapter/Ethernet-Kabel/NetApp-Ethernet-Kabel-CAT-6-2m-112-00195-X6561-R6.html"; //URL
//add
dataTableNewsletter.Rows.Add(row);
The exception: Exception from HRESULT: 0x800A03EC can be replicated by doing the following:
for (int i = 0; i < dataTableNewsletter.Rows.Count; i++)
{
//first row contains headers
int xlRowNum = i + 2;
string description = dataTableNewsletter.Rows[i]["Beschreibung"].ToString();
string url = dataTableNewsletter.Rows[i]["Shop-Link"].ToString();
//create hyperlink
Debug.WriteLine($"location: {i}, 11");
//The next line results in 'Exception from HRESULT: 0x800A03EC'
//because 0 is an invalid index in Excel
((Excel.Range)xlWSheet.Cells[i, 11]).Formula = $"=HYPERLINK(\"{url}\", \"{description}\")";
}
It looks like you are creating a .xls (older Excel) file instead of a .xlsx (newer Excel) file. If you create a .xlsx file you could use one of the following NuGet packages instead of Excel Interop:
DocumentFormat.OpenXml
ClosedXml
EPPlus
NPOI
Is the tab-delimited file something you just created for testing?
A tab-delimited file isn't really an Excel file. If you open Excel and select File => Save As, you'll see that a tab-delimited file is saved as a .txt file. When I opened the tab-delimited file in Excel it generated a warning about the file format not matching the file extension. If the tab-delimited file is saved with a .txt extension, Excel seems to open a wizard when the file is opened. This can be eliminated by naming the file with a .csv extension instead - although it's not really a .csv file either, but it doesn't seem to generate any warnings.
Since you're retrieving data from a database and stated that the data is already in a DataTable, it seems prudent to use the DataTable to create the Excel workbook.
Try the following (Excel Interop):
Create a new Windows Forms App (.NET Framework) project.
Then either download / install NuGet package: Microsoft.Office.Interop.Excel or add a reference to Microsoft Excel xx.x Object Library (Project => Add Reference...=> COM => Microsoft Excel xx.x Object Library (ex: Microsoft Excel 16.0 Object Library))
Add the following using directives:
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Data;
using System.Diagnostics;
CreateExcelWorkbook:
public static void CreateExcelWorkbook(DataTable dataTableNewsletter, string excelFilename)
{
Excel.Application xlApp = null;
Excel.Workbook xlWBook = null;
Excel.Worksheet xlWSheet = null;
Excel.Range allBZ = null;
Excel.Range exrngKopf = null;
try
{
if (dataTableNewsletter == null)
throw new Exception("Error - Data table is null.");
else if (dataTableNewsletter.Rows.Count <= 0)
throw new Exception($"Error - Data table doesn't contain any data.");
//create new instance
xlApp = new Excel.Application();
//whether or not to make Excel visible
xlApp.Visible = true;
//prevent prompting to overwrite existing file
xlApp.DisplayAlerts = false;
//disable user control while modifying the Excel Workbook
//to prevent user interference
//only necessary if Excel application Visibility property = true
//need to re-enable before exiting this method
//xlApp.UserControl = false;
//if writing/updating a large amount of data
//disable screen updating by setting value to false
//for better performance.
//re-enable when done writing/updating data, if desired
//excelApp.ScreenUpdating = false;
//add Workbook
xlWBook = xlApp.Workbooks.Add();
//activate
xlWBook.Activate();
if (xlWBook.Worksheets.Count > 0)
xlWSheet = (Excel.Worksheet)xlWBook.ActiveSheet;
else
xlWSheet = (Excel.Worksheet)xlWBook.Sheets.Add();
xlWSheet.Name = "GEKKO Computer GmbH";
//write column headers
//Excel indices start with 1; A1 = 1,1
for (int j = 0; j < dataTableNewsletter.Columns.Count; j++)
{
int xlColNum = j + 1;
//set value - column header
xlWSheet.Cells[1, xlColNum] = dataTableNewsletter.Columns[j].ColumnName;
//get range for column
//Excel.Range colRng = ((Excel.Range)xlWSheet.Cells[1, xlColNum]).EntireColumn;
//use DataTable data types to set data type for Excel column
//ToDo: change as desired
if (dataTableNewsletter.Columns[j].DataType.ToString() == "System.DateTime")
((Excel.Range)xlWSheet.Cells[1, xlColNum]).EntireColumn.NumberFormat = #"yyyy\-mm\-dd;#";
else if (dataTableNewsletter.Columns[j].DataType.ToString() == "System.Int32")
((Excel.Range)xlWSheet.Cells[1, xlColNum]).EntireColumn.NumberFormat = 0;
else if (dataTableNewsletter.Columns[j].DataType.ToString() == "System.Decimal")
((Excel.Range)xlWSheet.Cells[1, xlColNum]).EntireColumn.NumberFormat = "0.00";
}
//set values in Excel using data from DataTable
//ToDo: add desired code
for (int i = 0; i < dataTableNewsletter.Rows.Count; i++)
{
//Excel row numbers start with 1
//headers are in row 1, so data starts in row 2
int xlRowNum = i + 2;
for (int j = 0; j < dataTableNewsletter.Columns.Count; j++)
{
//Excel column numbers start with 1
int xlColNum = j + 1;
if (dataTableNewsletter.Rows[i][dataTableNewsletter.Columns[j].ColumnName] != null && dataTableNewsletter.Rows[i][dataTableNewsletter.Columns[j].ColumnName] != DBNull.Value)
{
//set cell value
xlWSheet.Cells[xlRowNum, xlColNum] = dataTableNewsletter.Rows[i][dataTableNewsletter.Columns[j].ColumnName].ToString();
}
}
}
//set value
allBZ = (Excel.Range)xlWSheet.UsedRange;
//Debug.WriteLine($"allBZ.Rows.Count: {allBZ.Rows.Count}; allBZ.Columns.Count: {allBZ.Columns.Count}");
//auto fit
allBZ.EntireColumn.AutoFit();
//set value
//exrngKopf = (Excel.Range)xlWSheet.Rows[1]; //row 1; header row
exrngKopf = (Excel.Range)xlWSheet.Cells[1, allBZ.Columns.Count]; //row 1; header row
exrngKopf.EntireRow.Font.Bold = true;
//set Border line style
xlWSheet.Cells.Borders.LineStyle = Excel.XlLineStyle.xlLineStyleNone;
xlWBook.Application.ActiveWindow.SplitRow = 1;
xlWBook.Application.ActiveWindow.FreezePanes = true;
if (xlWSheet.AutoFilter != null)
xlWSheet.AutoFilterMode = false;
xlWSheet.ListObjects.AddEx(Excel.XlListObjectSourceType.xlSrcRange, allBZ, Type.Missing, Excel.XlYesNoGuess.xlYes, Type.Missing).Name = "WFTableStyle";
xlWSheet.ListObjects.get_Item("WFTableStyle").TableStyle = null;
//fix hyperlinks
for (int i = 0; i < dataTableNewsletter.Rows.Count; i++)
{
//first row contains headers
int xlRowNum = i + 2;
//string description = dataTableNewsletter.Rows[i]["Beschreibung"].ToString();
string description = dataTableNewsletter.Rows[i]["Beschreibung"].ToString() + " - " + DateTime.Now.ToString("HH:mm:ss.fff");
string url = dataTableNewsletter.Rows[i]["Shop-Link"].ToString();
Debug.WriteLine($"Description: {description}; URL[{xlRowNum}, 11]: '{url}'");
//create hyperlink - option 1
//xlWSheet.Hyperlinks.Add(xlWSheet.Cells[xlRowNum, 11], url, System.Reflection.Missing.Value, description, description);
//create hyperlink - option 2
((Excel.Range)xlWSheet.Cells[xlRowNum, 11]).Formula = $"=HYPERLINK(\"{url}\", \"{description}\")"; //works
//Debug.WriteLine($"location: {i}, 11");
//((Excel.Range)xlWSheet.Cells[i, 11]).Formula = $"=HYPERLINK(\"{url}\", \"{description}\")"; //Exception from HRESULT: 0x800A03EC
}
//save Workbook - if file exists, overwrite it
//xlWBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookDefault, System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
xlWBook.SaveAs(excelFilename, Excel.XlFileFormat.xlWorkbookNormal, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
}
finally
{
if (xlWBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(allBZ);
System.Runtime.InteropServices.Marshal.ReleaseComObject(exrngKopf);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWSheet);
xlWSheet = null;
allBZ = null;
exrngKopf = null;
//close Workbook
xlWBook.Close(false);
//release all resources
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWBook);
xlWBook = null;
}
System.Threading.Thread.Sleep(150);
if (xlApp != null)
{
//quit
xlApp.Quit();
//release all resources
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(175);
}
}
}
Usage:
string excelFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "newsletter.xls");
HelperExcel.CreateExcelWorkbook(dataTableNewsletter, excelFilename);
//the following is necessary otherwise the Excel process seems to persist in Task Manager
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Resources:
Microsoft.Office.Interop.Excel Namespace
Range.EntireColumn Property
How do I get an Excel range using row and column numbers in VSTO / C#?
C# Excel how to add hyperlink with cell link
How To Create A Hyperlink Using Excel Hyperlink() Function In EPPlus .NET Application (C#) Part - Seven
How to automate Microsoft Excel from Microsoft Visual C#.NET
How to automate Excel by using Visual C# to fill or to obtain data in a range by using arrays
This question already has answers here:
Download Excel file via AJAX MVC
(15 answers)
How to download excel using ajax call?
(1 answer)
Closed 2 years ago.
I have a list of items from the database base that I will like to generate in excel and PDF. I want to do the excel first. I have not done this before, following a tutorial online I was able to get it to return FIle. But the problem is that I got "non invocable member 'File" cannot be used like a method". I have already used "using System.IO;"
Can someone help figure out what I am doing wrong
{
try
{
//var parameters = new { UserName = username, Password = password };
//var sql = "select * from users where username = #UserName and password = #Password";
//var result = connection.Query(sql, parameters);
IEnumerable<DailyInterest> dailyInterests = null;
var Id = id;
using (var conn = new SqlConnection(connectionstring))
{
await conn.OpenAsync();
//var parameters = new { Id = id };
dailyInterests = conn.Query<DailyInterest>("Select * from DailyInterest where LoanAccountNo=#Id", new { Id = id });
//step1: create array to holder header labels
string[] col_names = new string[]{
"Loan Account No",
"Transaction Amount",
"Interest Rate",
"Interest Amount",
"Original Loan Amount",
"Narration",
"DRCR",
"Transaction Date"
};
//step2: create result byte array
byte[] result;
//step3: create a new package using memory safe structure
using (var package = new ExcelPackage())
{
//step4: create a new worksheet
var worksheet = package.Workbook.Worksheets.Add("final");
//step5: fill in header row
//worksheet.Cells[row,col]. {Style, Value}
for (int i = 0; i < col_names.Length; i++)
{
worksheet.Cells[1, i + 1].Style.Font.Size = 14; //font
worksheet.Cells[1, i + 1].Value = col_names[i]; //value
worksheet.Cells[1, i + 1].Style.Font.Bold = true; //bold
//border the cell
worksheet.Cells[1, i + 1].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
//set background color for each sell
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(255, 243, 214));
}
int row = 8;
//step6: loop through query result and fill in cells
foreach (var item in dailyInterests)
{
for (int col = 1; col <= 2; col++)
{
worksheet.Cells[row, col].Style.Font.Size = 12;
//worksheet.Cells[row, col].Style.Font.Bold = true;
worksheet.Cells[row, col].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
}
//set row,column data
worksheet.Cells[row, 1].Value = item.LoanAccountNo;
worksheet.Cells[row, 2].Value = item.TranAmount;
worksheet.Cells[row, 3].Value = item.InterestRatePerDay;
worksheet.Cells[row, 4].Value = item.AmountPerDay;
worksheet.Cells[row, 5].Value = item.OriginalLoanAmount;
worksheet.Cells[row, 6].Value = item.Narration;
worksheet.Cells[row, 7].Value = item.DRCR;
worksheet.Cells[row, 8].Value = item.TranDate;
//toggle background color
//even row with ribbon style
if (row % 8 == 0)
{
worksheet.Cells[row, 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 1].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
worksheet.Cells[row, 2].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[row, 2].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(154, 211, 157));
}
row++;
}
//step7: auto fit columns
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
//step8: convert the package as byte array
result = package.GetAsByteArray();
}
//step9: return byte array as a file
**//This is where the error is**
return File(result, "application/vnd.ms-excel", "test.xls");
}
}
catch (Exception ex)
{
throw ex;
}
}
I have the following code to export data to an Excel sheet. I need your help to know how I can color the sheet columns in other colors?
System.Data.DataTable dit = null;
try
{
dit = BindGrid();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dit, "Students");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Download.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
catch (Exception Ex)
{
}
finally
{
dit = null;
}
using Excel = using Microsoft.Office.Interop.Excel
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
string path = excelFilename + ".xlsx";
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
worksheet.Cells[i + 2, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
workbook.SaveCopyAs(path);
workbook.Saved = true;
workbook.Close();
app.Quit();
}
Here i am exporting the datatables in a dataset to excel.How to make the header font of the datatable alone look bold.Here is my code
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
foreach (DataTable table in dtInputParameters.Tables)
{
dataExportExcel.DataSource = table;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
htmlWrite.WriteLine("<br/>");
// htmlWrite.AddStyleAttribute(System.Web.UI.HtmlTextWriterStyle.FontWeight, "bold");
}
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + worksheetName + "</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sbResponseString.Append(stringWriter + "<table width='800' height='100' align='center' style='text-align:center'");
sbResponseString.Append("</table></body></html>");
HttpContext.Current.Response.Write(sbResponseString.ToString());
HttpContext.Current.Response.End();
Any suggestion?
You need to set the HeaderStyle on the DataGrid to use bold font. That's all.
dataExportExcel.HeaderStyle.Font.Bold=true;
Cursor.Current = Cursors.WaitCursor;
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "Total Expiry Inventories Data ";
sfd.DefaultExt = "xls";
sfd.Filter = "xlsx files(*.xlsx)|*.xlsx";
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook workbook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook.Worksheets[1];
worksheet1.Name = "Expiry Data";
for (int i = 1; i < GrdViewData.Columns.Count + 1; i++)
{
worksheet1.Cells[1, i] = GrdViewData.Columns[i - 1].HeaderText;
worksheet1.Cells[1, i].Font.Bold = true;
}
for (int i = 0; i < GrdViewData.Rows.Count; i++)
{
for (int j = 0; j < GrdViewData.Columns.Count; j++)
{
worksheet1.Cells[i + 2, j + 1] = GrdViewData.Rows[i].Cells[j].Value.ToString();
}
}
worksheet1.Rows.Font.Size = 12;
// Excel.Range range_Consolidated = worksheet1.Rows.get_Range("a1", "d1");
// range_Consolidated.Font.Bold = true;
// range_Consolidated.Font.Italic = true;
string ExcelFileName = sfd.FileName;
workbook.SaveAs(ExcelFileName);
workbook.Close(false, ExcelFileName, Missing.Value);
ExcelApp.Quit();
ExcelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("File Saved! you can open it from\n '" + sfd.FileName + "'", "EXPORT", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
I have a DataTable with 30+ columns and 6500+ rows.I need to dump the whole DataTable values into an Excel file.Can anyone please help with the C# code.I need each column value to be in a cell.To be precise,I need the exact looking copy of DataTable in an Excel File.Please help.
Thanks,
Vix
use this code...
dt = city.GetAllCity();//your datatable
string attachment = "attachment; filename=city.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
This snippet could be faster to implement:
// Example data
DataTable table = new DataTable();
table.Columns.AddRange(new[]{ new DataColumn("Key"), new DataColumn("Value") });
foreach (string name in Request.ServerVariables)
table.Rows.Add(name, Request.ServerVariables[name]);
// This actually makes your HTML output to be downloaded as .xls file
Response.Clear();
Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
// Create a dynamic control, populate and render it
GridView excel = new GridView();
excel.DataSource = table;
excel.DataBind();
excel.RenderControl(new HtmlTextWriter(Response.Output));
Response.Flush();
Response.End();
Below link is used to export datatable to excel in C# Code.
http://royalarun.blogspot.in/2012/01/export-datatable-to-excel-in-c-windows.html
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace ExportExcel
{
public partial class ExportDatatabletoExcel : Form
{
public ExportDatatabletoExcel()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Add Datacolumn
DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));
dt.Columns.Add("LastName", typeof(String));
dt.Columns.Add("Blog", typeof(String));
dt.Columns.Add("City", typeof(String));
dt.Columns.Add("Country", typeof(String));
//Add in the datarow
DataRow newRow = dt.NewRow();
newRow["firstname"] = "Arun";
newRow["lastname"] = "Prakash";
newRow["Blog"] = "http://royalarun.blogspot.com/";
newRow["city"] = "Coimbatore";
newRow["country"] = "India";
dt.Rows.Add(newRow);
//open file
StreamWriter wr = new StreamWriter(#"D:\\Book1.xls");
try
{
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
The most rank answer in this post work, however its is CSV file. It is not actual Excel file. Therefore, you will get a warning when you are opening a file.
The best solution I found on the web is using CloseXML
https://github.com/closedxml/closedxml
You need to Open XML as well.
dt = city.GetAllCity();//your datatable
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
Credit: http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx
I use This in page.`
public void DTToExcel(DataTable dt)
{
// dosya isimleri ileride aynı anda birden fazla kullanıcı aynı dosya üzerinde işlem yapmak ister düşüncesiyle guid yapıldı.
string FileName = Guid.NewGuid().ToString();
FileInfo f = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));
if (f.Exists)
f.Delete(); // delete the file if it already exist.
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Charset = Encoding.UTF8.WebName;
response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
response.AddHeader("Content-Type", "application/Excel");
response.ContentType = "application/vnd.xlsx";
//response.AddHeader("Content-Length", file.Length.ToString());
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) //datatable'a aldığımız sorguyu bir datagrid'e atayıp html'e çevir.
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
dg.Dispose();
dt.Dispose();
response.End();
}
}
}
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv", lines);
Here dt refers to your DataTable pass as a paramter
While not a .NET implementation, you may find that the plug-in TableTools may be highly effective depending on your audience. It relies upon flash which shouldn't be a problem for most cases of needing to actually work in-depth and then want to record tabular information.
The latest version appears to support copying to clipboard, into a CSV, ".XLS" (really just a tab-delimited file named .xls), to a PDF, or create a printer friendly page version with all rows displayed and the rest of your page's contents hidden.
I found the extension on the DataTables site here: http://datatables.net/extras/tabletools/
The download is available in the plug-ins (extras) page here: http://datatables.net/extras/
It supposedly is downloaded as a part of DataTables (hence the phrase "Extras included in the DataTables package") but I didn't find it in the download I have been using. Seems to work wonderfully!
Most answers are actually producing the CSV which I don't always have good experience with, when opening in Excel.
One way of doing it would be also with ACE OLEDB Provider (see also connection strings for Excel). Of course you'd have to have the provider installed and registered. You do have it, if you have Excel installed, but this is something you have to consider when deploying (e.g. on web server).
In below helper class code you'd have to call something like ExportHelper.CreateXlsFromDataTable(dataset.Tables[0], #"C:\tmp\export.xls");
public class ExportHelper
{
private const string ExcelOleDbConnectionStringTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";";
/// <summary>
/// Creates the Excel file from items in DataTable and writes them to specified output file.
/// </summary>
public static void CreateXlsFromDataTable(DataTable dataTable, string fullFilePath)
{
string createTableWithHeaderScript = GenerateCreateTableCommand(dataTable);
using (var conn = new OleDbConnection(String.Format(ExcelOleDbConnectionStringTemplate, fullFilePath)))
{
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
OleDbCommand cmd = new OleDbCommand(createTableWithHeaderScript, conn);
cmd.ExecuteNonQuery();
foreach (DataRow dataExportRow in dataTable.Rows)
{
AddNewRow(conn, dataExportRow);
}
}
}
private static void AddNewRow(OleDbConnection conn, DataRow dataRow)
{
string insertCmd = GenerateInsertRowCommand(dataRow);
using (OleDbCommand cmd = new OleDbCommand(insertCmd, conn))
{
AddParametersWithValue(cmd, dataRow);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Generates the insert row command.
/// </summary>
private static string GenerateInsertRowCommand(DataRow dataRow)
{
var stringBuilder = new StringBuilder();
var columns = dataRow.Table.Columns.Cast<DataColumn>().ToList();
var columnNamesCommaSeparated = string.Join(",", columns.Select(x => x.Caption));
var questionmarkCommaSeparated = string.Join(",", columns.Select(x => "?"));
stringBuilder.AppendFormat("INSERT INTO [{0}] (", dataRow.Table.TableName);
stringBuilder.Append(columnNamesCommaSeparated);
stringBuilder.Append(") VALUES(");
stringBuilder.Append(questionmarkCommaSeparated);
stringBuilder.Append(")");
return stringBuilder.ToString();
}
/// <summary>
/// Adds the parameters with value.
/// </summary>
private static void AddParametersWithValue(OleDbCommand cmd, DataRow dataRow)
{
var paramNumber = 1;
for (int i = 0; i <= dataRow.Table.Columns.Count - 1; i++)
{
if (!ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(int)) && !ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(decimal)))
{
cmd.Parameters.AddWithValue("#p" + paramNumber, dataRow[i].ToString().Replace("'", "''"));
}
else
{
object value = GetParameterValue(dataRow[i]);
OleDbParameter parameter = cmd.Parameters.AddWithValue("#p" + paramNumber, value);
if (value is decimal)
{
parameter.OleDbType = OleDbType.Currency;
}
}
paramNumber = paramNumber + 1;
}
}
/// <summary>
/// Gets the formatted value for the OleDbParameter.
/// </summary>
private static object GetParameterValue(object value)
{
if (value is string)
{
return value.ToString().Replace("'", "''");
}
return value;
}
private static string GenerateCreateTableCommand(DataTable tableDefination)
{
StringBuilder stringBuilder = new StringBuilder();
bool firstcol = true;
stringBuilder.AppendFormat("CREATE TABLE [{0}] (", tableDefination.TableName);
foreach (DataColumn tableColumn in tableDefination.Columns)
{
if (!firstcol)
{
stringBuilder.Append(", ");
}
firstcol = false;
string columnDataType = "CHAR(255)";
switch (tableColumn.DataType.Name)
{
case "String":
columnDataType = "CHAR(255)";
break;
case "Int32":
columnDataType = "INTEGER";
break;
case "Decimal":
// Use currency instead of decimal because of bug described at
// http://social.msdn.microsoft.com/Forums/vstudio/en-US/5d6248a5-ef00-4f46-be9d-853207656bcc/localization-trouble-with-oledbparameter-and-decimal?forum=csharpgeneral
columnDataType = "CURRENCY";
break;
}
stringBuilder.AppendFormat("{0} {1}", tableColumn.ColumnName, columnDataType);
}
stringBuilder.Append(")");
return stringBuilder.ToString();
}
}
Working code for Excel Export
try
{
DataTable dt = DS.Tables[0];
string attachment = "attachment; filename=log.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception Ex)
{ }
Try this to export the data to Excel file same as in DataTable and could customize also.
dtDataTable1 = ds.Tables[0];
try
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
for (int i = 1; i > 0; i--)
{
Sheets xlSheets = null;
Worksheet xlWorksheet = null;
//Create Excel sheet
xlSheets = ExcelApp.Sheets;
xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlWorksheet.Name = "MY FIRST EXCEL FILE";
for (int j = 1; j < dtDataTable1.Columns.Count + 1; j++)
{
ExcelApp.Cells[i, j] = dtDataTable1.Columns[j - 1].ColumnName;
ExcelApp.Cells[1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
ExcelApp.Cells[i, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.WhiteSmoke);
}
// for the data of the excel
for (int k = 0; k < dtDataTable1.Rows.Count; k++)
{
for (int l = 0; l < dtDataTable1.Columns.Count; l++)
{
ExcelApp.Cells[k + 2, l + 1] = dtDataTable1.Rows[k].ItemArray[l].ToString();
}
}
ExcelApp.Columns.AutoFit();
}
((Worksheet)ExcelApp.ActiveWorkbook.Sheets[ExcelApp.ActiveWorkbook.Sheets.Count]).Delete();
ExcelApp.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you to export datatable to excel with formatted header text try like this.
public void ExportFullDetails()
{
Int16 id = Convert.ToInt16(Session["id"]);
DataTable registeredpeople = new DataTable();
registeredpeople = this.dataAccess.ExportDetails(eventid);
string attachment = "attachment; filename=Details.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
registeredpeople.Columns["Reg_id"].ColumnName = "Reg. ID";
registeredpeople.Columns["Name"].ColumnName = "Name";
registeredpeople.Columns["Reg_country"].ColumnName = "Country";
registeredpeople.Columns["Reg_city"].ColumnName = "City";
registeredpeople.Columns["Reg_email"].ColumnName = "Email";
registeredpeople.Columns["Reg_business_phone"].ColumnName = "Business Phone";
registeredpeople.Columns["Reg_mobile"].ColumnName = "Mobile";
registeredpeople.Columns["PositionRole"].ColumnName = "Position";
registeredpeople.Columns["Reg_work_type"].ColumnName = "Work Type";
foreach (DataColumn dc in registeredpeople.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in registeredpeople.Rows)
{
tab = "";
for (i = 0; i < registeredpeople.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
I have done the DataTable to Excel conversion with the following code. Hope it's very easy no need to change more just copy & pest the code replace your variable with your variable, and it will work properly.
First create a folder in your solution Document, and create an Excel file MyTemplate.xlsx. you can change those name according to your requirement. But remember for that you have to change the name in code also.
Please find the following code...
protected void GetExcel_Click(object sender, EventArgs e)
{
ManageTicketBS objManageTicket = new ManageTicketBS();
DataTable DT = objManageTicket.GetAlldataByDate(); //this function will bring the data in DataTable format, you can use your function instate of that.
string DownloadFileName;
string FolderPath;
string FileName = "MyTemplate.xlsx";
DownloadFileName = Path.GetFileNameWithoutExtension(FileName) + new Random().Next(10000, 99999) + Path.GetExtension(FileName);
FolderPath = ".\\" + DownloadFileName;
GetParents(Server.MapPath("~/Document/" + FileName), Server.MapPath("~/Document/" + DownloadFileName), DT);
string path = Server.MapPath("~/Document/" + FolderPath);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
try
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.ContentType = MimeType(Path.GetExtension(FolderPath));
response.AddHeader("Content-Disposition", "attachment;filename=" + DownloadFileName);
byte[] data = File.ReadAllBytes(path);
response.BinaryWrite(data);
HttpContext.Current.ApplicationInstance.CompleteRequest();
response.End();
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
DeleteOrganisationtoSupplierTemplate(path);
}
}
}
public string GetParents(string FilePath, string TempFilePath, DataTable DTTBL)
{
File.Copy(Path.Combine(FilePath), Path.Combine(TempFilePath), true);
FileInfo file = new FileInfo(TempFilePath);
try
{
DatatableToExcel(DTTBL, TempFilePath, 0);
return TempFilePath;
}
catch (Exception ex)
{
return "";
}
}
public static string MimeType(string Extension)
{
string mime = "application/octetstream";
if (string.IsNullOrEmpty(Extension))
return mime;
string ext = Extension.ToLower();
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (rk != null && rk.GetValue("Content Type") != null)
mime = rk.GetValue("Content Type").ToString();
return mime;
}
static bool DeleteOrganisationtoSupplierTemplate(string filePath)
{
try
{
File.Delete(filePath);
return true;
}
catch (IOException)
{
return false;
}
}
public void DatatableToExcel(DataTable dtable, string pFilePath, int excelSheetIndex=1)
{
try
{
if (dtable != null && dtable.Rows.Count > 0)
{
IWorkbook workbook = null;
ISheet worksheet = null;
using (FileStream stream = new FileStream(pFilePath, FileMode.Open, FileAccess.ReadWrite))
{
workbook = WorkbookFactory.Create(stream);
worksheet = workbook.GetSheetAt(excelSheetIndex);
int iRow = 1;
foreach (DataRow row in dtable.Rows)
{
IRow file = worksheet.CreateRow(iRow);
int iCol = 0;
foreach (DataColumn column in dtable.Columns)
{
ICell cell = null;
object cellValue = row[iCol];
switch (column.DataType.ToString())
{
case "System.Boolean":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.Boolean);
if (Convert.ToBoolean(cellValue)) { cell.SetCellFormula("TRUE()"); }
else { cell.SetCellFormula("FALSE()"); }
//cell.CellStyle = _boolCellStyle;
}
break;
case "System.String":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.String);
cell.SetCellValue(Convert.ToString(cellValue));
}
break;
case "System.Int32":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToInt32(cellValue));
//cell.CellStyle = _intCellStyle;
}
break;
case "System.Int64":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToInt64(cellValue));
//cell.CellStyle = _intCellStyle;
}
break;
case "System.Decimal":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(cellValue));
//cell.CellStyle = _doubleCellStyle;
}
break;
case "System.Double":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(cellValue));
//cell.CellStyle = _doubleCellStyle;
}
break;
case "System.DateTime":
if (cellValue != DBNull.Value)
{
cell = file.CreateCell(iCol, CellType.String);
DateTime dateTime = Convert.ToDateTime(cellValue);
cell.SetCellValue(dateTime.ToString("dd/MM/yyyy"));
DateTime cDate = Convert.ToDateTime(cellValue);
if (cDate != null && cDate.Hour > 0)
{
//cell.CellStyle = _dateTimeCellStyle;
}
else
{
// cell.CellStyle = _dateCellStyle;
}
}
break;
default:
break;
}
iCol++;
}
iRow++;
}
using (var WritetoExcelfile = new FileStream(pFilePath, FileMode.Create, FileAccess.ReadWrite))
{
workbook.Write(WritetoExcelfile);
WritetoExcelfile.Close();
//workbook.Write(stream);
stream.Close();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
This code you just need to copy & pest in your script and add the Namespace as following, Also change the excel file name as previously discussed.
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
Please try this, this will export your data table data's faster to excel.
Note: Range "FW", that I have hard coded is because I had 179 columns.
public void UpdateExcelApplication(SqlDataTable dataTable)
{
var objects = new string[dataTable.Rows.Count, dataTable.Columns.Count];
var rowIndex = 0;
foreach (DataRow row in dataTable.Rows)
{
var colIndex = 0;
foreach (DataColumn column in dataTable.Columns)
{
objects[rowIndex, colIndex++] = Convert.ToString(row[column]);
}
rowIndex++;
}
var range = this.workSheet.Range[$"A3:FW{dataTable.Rows.Count + 2}"];
range.Value = objects;
this.workSheet.Columns.AutoFit();
this.workSheet.Rows.AutoFit();
}