Export DataTable to Excel File - c#

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();
}

Related

Export datatable with 1 million records to csv

I have a C# Data Table with about one million rows with 20 columns
I need to export this to csv , i tried string builder but page keep loading
public ActionResult DownloadExcel()
{
System.Data.DataTable result = Helpers.TaxMailingExcelBuilder.Export();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=myData.csv");
Response.Charset = "";
Response.ContentType = #"application/text";
Response.Output.Write(ExportDataTable(result).ToString());
Response.Flush();
Response.End();
return View();
}
private StringBuilder ExportDataTable(System.Data.DataTable dt)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
stringBuilder.Append(dt.Rows[i][j].ToString() + ',');
}
stringBuilder.Append("rn");
}
return stringBuilder;
}
}
page keep loading without any progress
I would return a StringWriter like code below
private StringWriter ExportDataTable(DataTable dt)
{
StringWriter writer = new StringWriter();
string[] columnNames = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
writer.WriteLine(string.Join(",", columnNames));
foreach(DataRow row in dt.AsEnumerable())
{
writer.WriteLine(string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
return writer;
}

how can I save the excel from datagrid using epplus?

void Export()
{
string filePath = "";
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Excel | *.xlsx | Excel 2003 | *.xls";
if (dialog.ShowDialog() == true)
{
filePath = dialog.FileName;
}
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("Link is not valid");
return;
}
DataTable dt = new DataTable();
dtgExcel.DataContext = dt;
using (ExcelPackage excel = new ExcelPackage())
{
var ws = excel.Workbook.Worksheets.Add("Sheet1");
ws.Cells[1,1].LoadFromDataTable(dt, true);
ws.Cells.AutoFitColumns();
using (ExcelRange objRange = ws.Cells["A1:XFD1"])
{
objRange.Style.Font.Bold = true;
objRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
objRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
objRange.Style.Fill.PatternType = ExcelFillStyle.Solid; objRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#B7DEE8"));
}
FileStream file = File.Create(filePath);
file.Close();
File.WriteAllBytes(filePath, excel.GetAsByteArray());
}
MessageBox.Show("It's successful!!");
}
I take this event with the button and it return to "System.ArgumentException: 'Column out of range'"
Can you solve this problem for me?
Thanks a lot.
I'm thinking it must have something to do with the dataTable you're passing. What does the data you're using look like?
The below example works using both ws.Cells[1,1] or ws.Cells["A1"]
class Program
{
static void Main(string[] args)
{
ExcelPackage p = new ExcelPackage();
try
{
p = new ExcelPackage();
}
catch (System.IO.IOException fex)
{
//file is open
Console.WriteLine("Can not process while file is open.Please close file and try again.");
return;
}
catch (System.IO.InvalidDataException lex)
{
//invalid file type
Console.WriteLine("Invalid File Type. Please Try Again.");
return;
}
catch (Exception ex)
{
Console.WriteLine("Unhandled Exception. Please Contact Developer.");
return;
}
var wb = p.Workbook;
//create table
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Col1"));
dt.Columns.Add(new DataColumn("Col2"));
dt.Columns.Add(new DataColumn("Col3"));
dt.Columns.Add(new DataColumn("Col4"));
dt.Columns.Add(new DataColumn("Col5"));
//fill table
DataRow workRow;
for (int i = 0; i <= 9; i++)
{
workRow = dt.NewRow();
workRow["Col1"] = string.Format("Row {0} Col 1", i);
workRow["Col2"] = string.Format("Row {0} Col 2", i);
workRow["Col3"] = string.Format("Row {0} Col 3", i);
workRow["Col4"] = string.Format("Row {0} Col 4", i);
workRow["Col5"] = string.Format("Row {0} Col 5", i);
dt.Rows.Add(workRow);
}
//create worksheet
var ws = wb.Worksheets.Add("Foo");
//load data into cell A1
ws.Cells["A1"].LoadFromDataTable(dt, true);
ws.Cells.AutoFitColumns();
using (ExcelRange objRange = ws.Cells["A1:XFD1"])
{
objRange.Style.Font.Bold = true;
objRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
objRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
objRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
objRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#B7DEE8"));
}
p.SaveAs(new FileInfo(#"C:\FooFolder\Foo.xlsx"));
Console.WriteLine("It's Successful");
}
}

Export nested Gridview blank cell error

I followed this guide : Export Multi-Level Nested GridView to Excel using OpenXml in ASP.Net
And modified the code for my case as follows:
protected void ExportExcel(object sender, EventArgs e)
{
var dt = new DataTable("GridView_Data");
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
if (cell.Text != " ")
{
dt.Columns.Add(cell.Text);
}
}
foreach (GridViewRow row in grvPayroll.Rows)
{
var grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (var j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text,
grvPayrollDetailscell.Rows[j].Cells[2].Text);
}
}
using (var 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 (var MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
No error occurred, but the export file just contain the header , all cells are empty. The export excel file with exactly the header name and the number of rows. Why? Please help!
Here is the picture:
Exported File

Using Microsoft.office.interop.Excel Date format issue after exporting Data Table To Excel

My full Code is working well except the date field in the excel file after exporting. i am passing the date field as dd/MM/yyyy data with data table but in excel i am having an issue for few rows. for example :in case of February month of 2015 if the date is in between 01/02/2015 to 12/02/2015 then it is showing as 02/01/2015 - 02/12/2015 in exported excel file . but if date is greater than or equal to 13/02/2015 then it is showing perfect. Please help.
This is the class file i wrote :
public class InteropExportToExcel
{
public InteropExportToExcel()
{
}
public static void ExportExcel(DataTable dt, string SetFileName)
{
if (dt == null || dt.Rows.Count == 0) return;
var xlApp = new Excel.Application();
//Is this used?
CultureInfo CurrentCI = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Range range;
Excel.Workbook workbook = workbooks.Add();
Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (var r = 0; r < dt.Rows.Count; r++)
{
for (var i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
rowRead++;
//is this used?
percent = ((float)(100 * rowRead)) / totalCount;
}
Microsoft.Office.Interop.Excel.Range columns = worksheet.UsedRange.Columns;
columns.AutoFit();
//worksheet.Rows[1].Insert();
Excel.Range newRow = (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[1];
Excel.Range newCell = (Microsoft.Office.Interop.Excel.Range)newRow.Cells[1];
//newCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
//xlApp.Visible = true;
string fileName = HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName+".xlsx"); //Deleting Previous TempFile Before Saving.
if (fileName != null || fileName != string.Empty)
{
if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
}
workbook.SaveAs(HttpContext.Current.Server.MapPath("~/TempFiles/"+SetFileName), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Saving Current Excel Report in TempFile Server Folder
workbook.Close();
String FileName = SetFileName + ".xlsx"; // Code to Open Save Dialog in Client Computer.
String FilePath = HttpContext.Current.Server.MapPath("~/TempFiles/");
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
response.End();
}
public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
Calling the method of this class from the linkButton's Click event :
protected void lnkExportToExcel_lnkExportToExcel(object sender, EventArgs e)
{
int CustomPageSize = 99999999;
int CustomPageNumber = 1;
string FromDate = txtFromDate.Text;
string ToDate = txtToDate.Text;
List<int> OutputVal = new List<int>();
DataTable dtDailyComments = new DataTable();
PageSize = gvDailyComments.PageSize;
dtDailyComments = UserClass.GetDailyComments(FromDate, ToDate, CustomPageNumber, CustomPageSize, ref OutputVal);
var resultSet = from row in dtDailyComments.AsEnumerable() //Selecting Custom Selected Columns From DataTable
select new
{
SlNo = row["SlNo"].ToString(),
Comment_Date = row["CommentDate"].ToString(),
Subject = row["CommentSubject"].ToString(),
Comment = row["Comment"].ToString()
};
string SetFileName = "Daily_Comments_Report";
DataTable newDataTable = InteropExportToExcel.ConvertToDataTable(resultSet.ToList());
InteropExportToExcel.ExportExcel(newDataTable, SetFileName);
}
I managed to fix this issue by converting the date columns from database in 106 format. but why cant i use 103 format from database. that is dd/MM/yyyy. if possible then please tell me how to handle this issue.
If you like to set the format to dd/MM/yyyy try this:
...
try
{
if (dgvData.Rows.Count > 0)
{
xCellApp.Application.Workbooks.Add(Type.Missing);
for (int i = 1; i < dgvData.Columns.Count + 1; i++)
{
xCellApp.Cells[1, i] = dgvData.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dgvData.Rows.Count - 1; i++)
{
for (int j = 0; j < dgvData.Columns.Count; j++)
{
if (dgvData.Columns[j].HeaderText == "dates")
{
DateTime dt = Convert.ToDateTime(dgvData.Rows[i].Cells[j].Value.ToString());
xCellApp.Cells[i + 2, j + 1] = dt.ToString("MM/dd/yyyy");
}
else
{
xCellApp.Cells[i + 2, j + 1] = dgvData.Rows[i].Cells[j].Value.ToString();
}
}
}
xCellApp.Columns.AutoFit();
xCellApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
xCellApp.Quit();
}
}

Export SQL to Excel

How can i export my data from SQL server 2008 into Excel 2010 or later ?
i have tried on SQL way:
sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 0;
GO
RECONFIGURE;
GO
INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls;Extended Properties=EXCEL 12.0;HDR=YES',
'SELECT NO_ORDRE, Date FROM [Sheet1$]')
SELECT [NO_ORDRE], GETDATE() FROM ORDRE
GO
Unfortuntely i receive error:
The OLE DB provider 'Microsoft.Jet.OLEDB.4.0' can not be used for distributed queries because the provider is configured to run in STA mode.
and then i tried on C# way:
public class ExportToExcel
{
private Excel.Application app;
private Excel.Workbook workbook;
private Excel.Worksheet previousWorksheet;
// private Excel.Range workSheet_range;
private string folder;
public ExportToExcel(string folder)
{
this.folder = folder;
this.app = null;
this.workbook = null;
this.previousWorksheet = null;
// this.workSheet_range = null;
createDoc();
}
private void createDoc()
{
try
{
app = new Excel.Application();
app.Visible = false;
workbook = app.Workbooks.Add(1);
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}
public void shutDown()
{
try
{
workbook = null;
app.Quit();
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}
public void ExportTable(string query, string sheetName)
{
SqlDataReader myReader = null;
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
worksheet.Name = sheetName;
previousWorksheet = worksheet;
SqlCommand myCommand = new SqlCommand(query, connectionWrapper.conn);
myReader = myCommand.ExecuteReader();
int columnCount = myReader.FieldCount;
for (int n = 0; n < columnCount; n++)
{
//Console.Write(myReader.GetName(n) + "\t");
createHeaders(worksheet, 1, n + 1, myReader.GetName(n));
}
int rowCounter = 2;
while (myReader.Read())
{
for (int n = 0; n < columnCount; n++)
{
//Console.WriteLine();
//Console.Write(myReader[myReader.GetName(n)].ToString() + "\t");
addData(worksheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());
}
rowCounter++;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
if (myReader != null && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
}
}
public void createHeaders(Excel.Worksheet worksheet, int row, int col, string htext)
{
worksheet.Cells[row, col] = htext;
}
public void addData(Excel.Worksheet worksheet, int row, int col, string data)
{
worksheet.Cells[row, col] = data;
}
public void SaveWorkbook()
{
String folderPath = "C:\\My Files\\" + this.folder;
if (!System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.CreateDirectory(folderPath);
}
string fileNameBase = "db";
String fileName = fileNameBase;
string ext = ".xlsx";
int counter = 1;
while (System.IO.File.Exists(folderPath + fileName + ext))
{
fileName = fileNameBase + counter;
counter++;
}
fileName = fileName + ext;
string filePath = folderPath + fileName;
try
{
workbook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
unfortunately i got error:
Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
Any idea how can i export SQL to Excel ?
Your best bet might be to just write it out to a CSV. Excel registers itself as the file handler for CSV files, so it will open in excel by default.
For example:
private void SQLToCSV(string query, string Filename)
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
{
// Loop through the fields and add headers
for (int i = 0; i < dr.FieldCount; i++)
{
string name = dr.GetName(i);
if (name.Contains(","))
name = "\"" + name + "\"";
fs.Write(name + ",");
}
fs.WriteLine();
// Loop through the rows and output the data
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
string value = dr[i].ToString();
if (value.Contains(","))
value = "\"" + value + "\"";
fs.Write(value + ",");
}
fs.WriteLine();
}
fs.Close();
}
}
C# SQL to Excel
Call you SP from Database
public DataTable GetDrugUtilizationReport_IndividualGenerateFile(long pharmacyId, DateTime from, DateTime to, long DrugNameId, int sortBy)
{
var parameters = new Dictionary<string, object>
{
{ "PharmacyId", pharmacyId },
{ "DateFrom", from },
{ "DateTo", to },
{ "DrugNameId", DrugNameId },
{ "SortBy", sortBy }
};
return ExecuteQuery("RPT_DrugUtilizationReportByIndividualGenerateFile", CommandType.StoredProcedure, parameters);
}
Use in your C# Code
private void OnCreateFileCommand(object obj)
{
string path, parameterLabel;
path = ConfigurationManager.AppSettings["VSSPORTEXELExportPath"];
parameterLabel = FromDate.ToString("yyyy-MM-dd") + "_" + ToDate.ToString("yyyy-MM-dd");
try
{
path =
ExcelUtlity.ExportDataToExcel(
dataTable:
context.GetDrugUtilizationReport_IndividualGenerateFile(GlobalVar.Pharminfo.pharminfo_PK,
FromDate, ToDate, SelectedDrug != null ? SelectedDrug.drugnameid_PK : 0,
sortBy: SortBy + 1),
directoryPath: path,
fileName_withoutExt: "DrugUtilizationReport" + "__" + parameterLabel,
skipComplexObjects: true,
skipInheritedProps: true);
DXMessageBox.Show("Data exported successfully at \"" + path + "\".", GlobalVar.MessageTitle,
MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
string errorMessage = ExceptionHelper.ProcessException(ex);
DXMessageBox.Show(errorMessage, GlobalVar.MessageTitle, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Excel Utility
public static string ExportDataToExcel(DataTable dataTable, string directoryPath, string fileName_withoutExt, bool skipComplexObjects, bool skipInheritedProps, string[] skipProps = null)
{
if (directoryPath[directoryPath.Length - 1] == '\\') // no need to check for >0 length. let it throw an exection for that
directoryPath = directoryPath + "\\";
using (var spreadSheet = new SpreadsheetControl())
{
// Create new excel document and import the datatable to the worksheet
spreadSheet.CreateNewDocument();
spreadSheet.BeginUpdate();
var worksheet = spreadSheet.Document.Worksheets.ActiveWorksheet;
worksheet.Import(source: dataTable, addHeader: true, firstRowIndex: 0, firstColumnIndex: 0);
// applying style on header
Range range = worksheet.Range["A1:" + worksheet.Columns[worksheet.Columns.LastUsedIndex].Heading+"1"];
Formatting rangeFormatting = range.BeginUpdateFormatting();
rangeFormatting.Fill.BackgroundColor = System.Drawing.Color.LightSteelBlue;
rangeFormatting.Font.FontStyle = SpreadsheetFontStyle.Bold;
range.AutoFitColumns();
range.EndUpdateFormatting(rangeFormatting);
spreadSheet.EndUpdate();
fileName_withoutExt += ".xlsx";
Directory.CreateDirectory(directoryPath); // if directory already exists, CreateDirectory will do nothing
spreadSheet.SaveDocument(directoryPath + fileName_withoutExt, DocumentFormat.OpenXml);
return directoryPath + fileName_withoutExt;
}
}
Using Microsoft Office dll
public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)
{
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
try
{
// Start Excel and get Application object.
excel = new Microsoft.Office.Interop.Excel.Application();
// for making Excel visible
excel.Visible = false;
excel.DisplayAlerts = false;
// Creation a new Workbook
excelworkBook = excel.Workbooks.Add(Type.Missing);
// Workk sheet
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
excelSheet.Name = worksheetName;
excelSheet.Cells[1, 1] = ReporType;
excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();
// loop through each row and add values to our sheet
int rowcount = 2;
foreach (DataRow datarow in dataTable.Rows)
{
rowcount += 1;
for (int i = 1; i <= dataTable.Columns.Count; i++)
{
// on the first iteration we add the column headers
if (rowcount == 3)
{
excelSheet.Cells[2, i] = dataTable.Columns[i - 1].ColumnName;
excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
}
excelSheet.Cells[rowcount, i] = datarow[i - 1].ToString();
//for alternate rows
if (rowcount > 3)
{
if (i == dataTable.Columns.Count)
{
if (rowcount % 2 == 0)
{
excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
}
}
}
}
}
// now we resize the columns
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, dataTable.Columns.Count]];
excelCellrange.EntireColumn.AutoFit();
Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
border.Weight = 2d;
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[2, dataTable.Columns.Count]];
FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
//now save the workbook and exit Excel
excelworkBook.SaveAs(saveAsLocation); ;
excelworkBook.Close();
excel.Quit();
return true;
}
catch (Exception ex)
{
DXMessageBox.Show(ex.Message);
return false;
}
finally
{
excelSheet = null;
excelCellrange = null;
excelworkBook = null;
}
}
/// <summary>
/// FUNCTION FOR FORMATTING EXCEL CELLS
/// </summary>
/// <param name="range"></param>
/// <param name="HTMLcolorCode"></param>
/// <param name="fontColor"></param>
/// <param name="IsFontbool"></param>
public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
{
range.Interior.Color = System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
if (IsFontbool == true)
{
range.Font.Bold = IsFontbool;
}
}
I have modified code which was given above as and is working. Edit according to your requirements
namespace ExcelExport
{
public class ExportToExcel
{
string strCon = ConfigurationManager.ConnectionStrings["SafewayGVDemoDBContext"].ConnectionString;
private Microsoft.Office.Interop.Excel.Application app;
private Microsoft.Office.Interop.Excel.Workbook workbook;
private Microsoft.Office.Interop.Excel.Worksheet previousWorksheet;
// private Excel.Range workSheet_range;
private string folder;
public ExportToExcel(string folder)
{
this.folder = folder;
this.app = null;
this.workbook = null;
this.previousWorksheet = null;
// this.workSheet_range = null;
createDoc();
}
private void createDoc()
{
try
{
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
workbook = app.Workbooks.Add(1);
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}
public void shutDown()
{
try
{
workbook = null;
app.Quit();
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
finally
{
}
}
public void ExportTable(string procName, string sheetName)
{
SqlDataReader myReader = null;
try
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets.Add(Missing.Value, Missing.Value, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
using (SqlConnection Sqlcon = new SqlConnection(strCon))
{
SqlCommand cmd = new SqlCommand();
Sqlcon.Open();
cmd.Connection = Sqlcon;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procName;
cmd.Parameters.Add(new SqlParameter("#pvchAction", SqlDbType.VarChar, 50));
cmd.Parameters.Add("#pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Parameters["#pvchAction"].Value = "select";
worksheet.Name = sheetName;
previousWorksheet = worksheet;
myReader = cmd.ExecuteReader();
int columnCount = myReader.FieldCount;
for (int n = 0; n < columnCount; n++)
{
//Console.Write(myReader.GetName(n) + "\t");
createHeaders(worksheet, 1, n + 1, myReader.GetName(n));
}
int rowCounter = 2;
while (myReader.Read())
{
for (int n = 0; n < columnCount; n++)
{
//Console.WriteLine();
//Console.Write(myReader[myReader.GetName(n)].ToString() + "\t");
addData(worksheet, rowCounter, n + 1, myReader[myReader.GetName(n)].ToString());
}
rowCounter++;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
if (myReader != null && !myReader.IsClosed)
{
myReader.Close();
}
myReader = null;
}
}
public void createHeaders(Microsoft.Office.Interop.Excel.Worksheet worksheet, int row, int col, string htext)
{
worksheet.Cells[row, col] = htext;
}
public void addData(Microsoft.Office.Interop.Excel.Worksheet worksheet, int row, int col, string data)
{
worksheet.Cells[row, col] = data;
}
public void SaveWorkbook()
{
String folderPath = #"C:\My Files\" + this.folder;
if (!System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.CreateDirectory(folderPath);
}
string fileNameBase = "db";
String fileName = fileNameBase;
string ext = ".xlsx";
int counter = 1;
//System.IO.File.Open(folderPath + fileName + ext, System.IO.FileMode.Open);
while (System.IO.File.Exists(folderPath + #"\"+ fileName + ext))
{
fileName = fileNameBase + counter;
counter++;
}
fileName = fileName + ext;
string filePath = folderPath +#"\"+ fileName;
try
{
workbook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Since you're using Excel 2010 the easiest solution is to download PowerPivot from Microsoft and execute the SQL query directly. This will create a refreshable data connection that pulls the data from the Query into a pivot table.
http://www.microsoft.com/bi/en-us/Solutions/Pages/PowerPivot.aspx
This is hundred percent working for VS-2013 Premium for C# for Coded UI testing. just copy and paste the code That's it. Its working for SQL Server database You can save the data into xls, xlsx, or csv and can use that same csv for parameterization. you need to install following packages to make it work.
using System.Data.SqlClient
using Excel=Microsoft.Office.Interop.Excel
using SQL = System.Data
///***Copy from here and paste it under / To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
SqlConnection cnn;
string connectionstring = null;
string sql = null;
string data = null;
int i = 0;
int j = 0;
////*** Preparing excel Application
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
///*** Opening Excel application
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(#"C:\Users\MM18100\Documents\Visual Studio 2013\Projects\SQL\SQL\Book1.csv");
xlWorkSheet = (Excel.Worksheet)(xlWorkBook.ActiveSheet as Excel.Worksheet);
////*** It will always remove the prvious result from the CSV file so that we can get always the updated data
xlWorkSheet.UsedRange.Select();
xlWorkSheet.UsedRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
xlApp.DisplayAlerts = false;
//xlWorkBook.Save();
/////***Opening SQL Database
connectionstring = "Integrated Security = SSPI;Initial Catalog=Exascale; Data Source=DCNA-Q-SQL-07;";
cnn = new SqlConnection(connectionstring);
cnn.Open();
////** Write your Sql Query here
sql = "SELECT TOP 10 [FirstName],[MiddleName],[LastName],[Email],[AltEmail],[Phone],[AltPhoneNumber],[Mobile],[Fax],[CompanyName],[AuthorizedUserName],[AuthorizedUserPhone],[CreatedDate],[ModifiedDate],[VERSION],[LanguageID],[TaxID],[CustomerType]FROM [Exascale].[dbo].[Customer] Where [FirstName] = 'Automation'";
///*** Preparing to retrieve value from the database
SQL.DataTable dtable = new SQL.DataTable();
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
SQL.DataSet ds = new SQL.DataSet();
dscmd.Fill(dtable);
////*** Generating the column Names here
string[] colNames = new string[dtable.Columns.Count];
int col = 0;
foreach (SQL.DataColumn dc in dtable.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dtable.Columns.Count - 1);
xlWorkSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
xlWorkSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
xlWorkSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;
/////*** Inserting the Column and Values into Excel file
for (i = 0 ; i <= dtable.Rows.Count - 1; i++)
{
for (j = 0; j <= dtable.Columns.Count-1; j++)
{
data = dtable.Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
///**Saving the csv file without notification.
xlApp.DisplayAlerts = false;
xlWorkBook.Save();
//xlWorkBook.SaveAs("Book1.csv", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
////MessageBox.Show("Excel file created , you can find the file C:\\Users\\MM18100\\Documents\\informations.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void button1_Click(object sender, EventArgs e)
{
string StartDate = Start_Date.Value.Date.ToString("MM/dd/yyyy").Replace("-", "/");
string EndDate = End_Date.Value.Date.ToString("MM/dd/yyyy").Replace("-", "/");
string LogFolder = #"C:\Log\";
try
{
string StoredProcedureName = comboBox1.Text;
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = ConnectionString;
//Load Data into DataTable from by executing Stored Procedure
string queryString =
"EXEC " + StoredProcedureName + " #Ifromdate ='" + StartDate + "',#Itodate ='" + EndDate+"'";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable DtValue = new DataTable();
DtValue = (ds.Tables[0]);
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
}
}
}
///JUST add ClosedXMl.dll
public void DataTableToExcel(DataTable dt)
{
string FileName = "Records";
string SheetName = "Records";
string folderPath = "C:\\New\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, SheetName);
wb.SaveAs(folderPath + "\\" + FileName + ".xlsx");
}
}
ExcelPackage EP = new ExcelPackage();
ExcelWorksheet Sheet =
EP.Workbook.Worksheets.Add("subscriptions");
Sheet.Cells["A1"].Value = "Email";
Sheet.Cells["A1"].Style.Font.Bold = true;
Sheet.Cells["B1"].Value = "First Name";
Sheet.Cells["B1"].Style.Font.Bold = true;
Sheet.Cells["C1"].Value = "Middle Name";
Sheet.Cells["C1"].Style.Font.Bold = true;
Sheet.Cells["D1"].Value = "Last Name";
Sheet.Cells["D1"].Style.Font.Bold = true;
Sheet.Cells["E1"].Value = "Date Created";
Sheet.Cells["E1"].Style.Font.Bold = true;
Sheet.Cells["F1"].Value = "Subscribed";
Sheet.Cells["F1"].Style.Font.Bold = true;
var collection = MyRepository.GetSubscriptionsAll();
int row = 2;
foreach (var item in collection)
{
Sheet.Cells[string.Format("A{0}", row)].Value = item.Email;
Sheet.Cells[string.Format("B{0}", row)].Value
=item.FistName;
Sheet.Cells[string.Format("C{0}", row)].Value
=item.MiddleName;
Sheet.Cells[string.Format("D{0}", row)].Value
=item.LastName;
Sheet.Cells[string.Format("E{0}", row)].Value =
.DateCreated.ToString();
Sheet.Cells[string.Format("F{0}", row)].Value =
(item.Subscribed == false
? "No" : "Yes"); ;
row++;
}
Sheet.Cells["A:AZ"].AutoFitColumns();
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Web.HttpContext.Current.Response.AddHeader("content-
disposition",
"attachment: filename=" + "ListofSubscribers.xlsx");
System.Web.HttpContext.Current.Response.BinaryWrite(EP.GetAsByteArray());
System.Web.HttpContext.Current.Response.End();
}
Excel 2016 and newer comes with something called Power Query (Older versions will also work but require a separate install). With this tool you can pull data directly from a database into excel.
On the "Data" tab in Excel select "Get Data" --> "From Database" --> "From SQL Server database". Put in the database information and under "Advanced options" you can paste your SQL query in and pull the data directly in Excel. This works for many different database types, flat files and other sources.
2 simple options would be:
1) to use the SQL server import and export wizard, which you can use to Export any table from your database in Excel (Just make sure the mapping is correct)
2) Would be just to run your sql statement and then in your results window below, select all and right click and do a 'Copy with Headers' and then just paste the results in Excel
Bind your data into a grid view....and use the following code .....
protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView2.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Categories