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();
}
I have a datagridview and already have a export function using Microsoft interop however i am struggling to find a solution to the loading the data.
My code to export to Excel:
private void iSave()
{
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["Journal"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from Journal Pro";
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();
}
}
}
I also want it to add data from the second row as the first row is the title of the columns.
If theres a solution to use excel to load data in using the same format which is exported in i would be grateful :)
I am also open to other methods of saving, it doesn't have to be to an excel file.
I have used some other codes found online such as
`
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files Only | *.xlsx; *.xls";
ofd.Title = "Choose the File";
if (ofd.ShowDialog() == DialogResult.OK)
FileName_LBL.Text = ofd.FileName;
}
Microsoft.Office.Interop.Excel._Application xlapp;
Microsoft.Office.Interop.Excel._Workbook xlworkbook;
Microsoft.Office.Interop.Excel._Worksheet xlworksheet;
Microsoft.Office.Interop.Excel._Worksheet xlrange;
try
{
xlapp = new Microsoft.Office.Interop.Excel.Application();
xlworkbook = xlapp.Workbooks.Open(FileName_LBL.Text);
xlworksheet = xlworkbook.Worksheets["Exported from Journal Pro"];
xlrange = (Microsoft.Office.Interop.Excel._Worksheet)xlworksheet.UsedRange;
dataGridView1.ColumnCount = xlrange.Columns.Count;
for (int xlrow = 2; xlrow <= xlrange.Rows.Count; xlrow++)
{
dataGridView1.Rows.Add(xlrange.Cells[xlrow, 2].Text, xlrange.Cells[xlrow, 3].Text, xlrange.Cells[xlrow, 4].Text, xlrange.Cells[xlrow, 5].Text, xlrange.Cells[xlrow, 6].Text, xlrange.Cells[xlrow, 7].Text);
}
xlworkbook.Close();
xlapp.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
`
but i get errors such as DISP_E_BADINDEX and E_NOINTERFACE
You can use this method to finish loading the data.
Step 1: Convert dataGridView to dataTable.
Step 2: Export dataTable to Excel .
Step 3: button calls the OutputExcel method.
Full Code
private void button1_Click(object sender, EventArgs e)
{
OutputExcel(dataGridView1);
}
public void OutputExcel(DataGridView dataGridView)
{
string filePath = "";
SaveFileDialog s = new SaveFileDialog();
s.Title = "Excel";
s.Filter = "Excel(*.xlsx)|*.xlsx";
s.FilterIndex = 1;
if (s.ShowDialog() == DialogResult.OK)
filePath = s.FileName;
else
return;
//Step 1: Convert dataGridView to dataTable
DataTable tmpDataTable = new DataTable("tmpDataTable");
DataTable modelTable = new DataTable("ModelTable");
for (int column = 0; column < dataGridView.Columns.Count; column++)
{
if (dataGridView.Columns[column].Visible == true)
{
DataColumn tempColumn = new DataColumn(dataGridView.Columns[column].HeaderText, typeof(string));
tmpDataTable.Columns.Add(tempColumn);
DataColumn modelColumn = new DataColumn(dataGridView.Columns[column].Name, typeof(string));
modelTable.Columns.Add(modelColumn);
}
}
for (int row = 0; row < dataGridView.Rows.Count; row++)
{
if (dataGridView.Rows[row].Visible == false)
continue;
DataRow tempRow = tmpDataTable.NewRow();
for (int i = 0; i < tmpDataTable.Columns.Count; i++)
tempRow[i] = dataGridView.Rows[row].Cells[modelTable.Columns[i].ColumnName].Value;
tmpDataTable.Rows.Add(tempRow);
}
if (tmpDataTable == null)
{
return;
}
//Step 2: Export dataTable to Excel
long rowNum = tmpDataTable.Rows.Count;//line
int columnNum = tmpDataTable.Columns.Count;//column
Excel.Application m_xlApp = new Excel.Application();
m_xlApp.DisplayAlerts = false;
m_xlApp.Visible = false;
Excel.Workbooks workbooks = m_xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//Get sheet1
try
{
string[,] datas = new string[rowNum + 1, columnNum];
for (int i = 0; i < columnNum; i++) //Write field
datas[0, i] = tmpDataTable.Columns[i].Caption;
Excel.Range range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
range.Font.Size = 10;
int r = 0;
for (r = 0; r < rowNum; r++)
{
for (int i = 0; i < columnNum; i++)
{
object obj = tmpDataTable.Rows[r][tmpDataTable.Columns[i].ToString()];
datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();
}
Application.DoEvents();
}
Excel.Range fchR = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];
fchR.Value2 = datas;
worksheet.Columns.EntireColumn.AutoFit();
m_xlApp.Visible = false;
range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];
range.Font.Size = 9;
range.RowHeight = 14.25;
range.Borders.LineStyle = 1;
range.HorizontalAlignment = 1;
workbook.Saved = true;
workbook.SaveCopyAs(filePath);
}
catch (Exception ex)
{
MessageBox.Show("Export Exception:" + ex.Message, "Export Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
m_xlApp.Workbooks.Close();
m_xlApp.Workbooks.Application.Quit();
m_xlApp.Application.Quit();
m_xlApp.Quit();
MessageBox.Show("Export successful!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Effect:
Hope it can help you.
I'm new to c# and WPF and trying to import a large .xlsx file into a datagrid, i can have around 200+ columns & 100,000+ rows. With my current method it is taking over an hour (i didn't let it finish). An example of my format in csv terms would be;
"Time","Dist","V_Front","V_Rear","RPM"
"s","m","km/h","km/h","rpm"
"0.000","0","30.3","30.0","11995"
"0.005","0","30.3","30.0","11965"
"0.010","0","30.3","31.0","11962"
I'm using Interop at the moment but i'm wondering whether there is another approach which would drastically cut down load time. I hope to plot this data using SciCharts (they have a student licence), with check boxes for channel selection but that's another matter.
.CS
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
txtFilePath.Text = openfile.FileName;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(txtFilePath.Text.ToString(), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
string strCellData = "";
double douCellData;
int rowCnt = 0;
int colCnt = 0;
DataTable dt = new DataTable();
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
string strColumn = "";
strColumn = (string)(excelRange.Cells[1, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
dt.Columns.Add(strColumn, typeof(string));
}
for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)
{
string strData = "";
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
try
{
strCellData = (string)(excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += strCellData + "|";
}
catch (Exception ex)
{
douCellData = (excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += douCellData.ToString() + "|";
}
}
strData = strData.Remove(strData.Length - 1, 1);
dt.Rows.Add(strData.Split('|'));
}
dtGrid.ItemsSource = dt.DefaultView;
excelBook.Close(true, null, null);
excelApp.Quit();
}
}
Any help i really appreciated.
The problem is that there is too many individual reads which causes a lot of reflection usage and marshalling between Excel and your application. If you're not concerned about memory usage, you can just read the whole Range into memory and work from memory instead of individually reading cells. The below code runs in 3880 ms on a test file with 5 columns and 103938 rows:
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
txtFilePath.Text = openfile.FileName;
var excelApp = new Microsoft.Office.Interop.Excel.Application();
var excelBook = excelApp.Workbooks.Open(txtFilePath.Text, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
var excelSheet = (Microsoft.Office.Interop.Excel.Worksheet) excelBook.Worksheets.Item[1];
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
DataTable dt = new DataTable();
object[,] value = excelRange.Value;
int columnsCount = value.GetLength(1);
for (var colCnt = 1; colCnt <= columnsCount; colCnt++)
{
dt.Columns.Add((string)value[1, colCnt], typeof(string));
}
int rowsCount = value.GetLength(0);
for (var rowCnt = 2; rowCnt <= rowsCount; rowCnt++)
{
var dataRow = dt.NewRow();
for (var colCnt = 1; colCnt <= columnsCount; colCnt++)
{
dataRow[colCnt - 1] = value[rowCnt, colCnt];
}
dt.Rows.Add(dataRow);
}
dtGrid.ItemsSource = dt.DefaultView;
excelBook.Close(true);
excelApp.Quit();
}
If you don't want to read the whole Range in, then you should do that in sensible batches.
Another optimization is to run this on a background thread, so it won't block the UI while it's loading.
Edit
For running this on a background thread you could modify the button click handler to be an async method and put the parsing logic into another method which runs the actual parsing on a threadpool thread with Task.Run:
private async void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
txtFilePath.Text = openfile.FileName;
DataTable dataTable = await ParseExcel(txtFilePath.Text).ConfigureAwait(true);
dtGrid.ItemsSource = dataTable.DefaultView;
}
}
private Task<DataTable> ParseExcel(string filePath)
{
return Task.Run(() =>
{
var excelApp = new Microsoft.Office.Interop.Excel.Application();
var excelBook = excelApp.Workbooks.Open(filePath, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
var excelSheet = (Microsoft.Office.Interop.Excel.Worksheet) excelBook.Worksheets.Item[1];
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
DataTable dt = new DataTable();
object[,] value = excelRange.Value;
int columnsCount = value.GetLength(1);
for (var colCnt = 1; colCnt <= columnsCount; colCnt++)
{
dt.Columns.Add((string) value[1, colCnt], typeof(string));
}
int rowsCount = value.GetLength(0);
for (var rowCnt = 2; rowCnt <= rowsCount; rowCnt++)
{
var dataRow = dt.NewRow();
for (var colCnt = 1; colCnt <= columnsCount; colCnt++)
{
dataRow[colCnt - 1] = value[rowCnt, colCnt];
}
dt.Rows.Add(dataRow);
}
excelBook.Close(true);
excelApp.Quit();
return dt;
});
}
The handler just invokes the parsing function, the parsing function runs on a background thread and when it finishes the handler can continue by assigning the resulting DataTable to the ItemsSource.
I am using Microsoft.Office.Interop.Excel to export local database table to excel file. There are five columns.
If rows are 400 it takes about 20 seconds,
If rows are 1200 it takes about 45 seconds,
If rows are 5000 it takes 250-300 seconds.
Is there a way to minimize the time to export? Or this is the maximum performance? If you can suggest to improve my code with respect to speed or suggest some alternative, I will appreciate. As it is working in background worker therefore invoking was necessary. My code is
int rowCount = oLXTableDataGridView.RowCount;
if (rowCount == 1)
{
MessageBox.Show("No data to export.");
return;
}
this.Invoke((MethodInvoker)delegate
{
this.ExportFilepictureBox.Image = Properties.Resources.Animation;
labelexpoertolx.Text = "Preparing to export...";
});
object misValue = System.Reflection.Missing.Value;
conn = new SqlCeConnection(#"Data Source=|DataDirectory|\dontdelete.sdf");
String selectgroup = "SELECT * FROM OLXTable";
int namecol = 1;
int cellcol = 2;
int emailcol = 3;
int citycol = 4;
int categorycol = 5;
try
{
Excel.Application xlApp1;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
xlApp1 = new Excel.Application();
xlWorkBook = xlApp1.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// MessageBox.Show("this is file");
xlWorkSheet.Cells[1, namecol].Value2 = "Name";
xlWorkSheet.Cells[1, cellcol].Value2 = "Cell No";
xlWorkSheet.Cells[1, emailcol].Value2 = "Email";
xlWorkSheet.Cells[1, citycol].Value2 = "City";
xlWorkSheet.Cells[1, categorycol].Value2 = "Category";
SqlCeDataReader reader = null;
//conn = new SqlCeConnection(selectnumbers);
conn.Open(); //open the connection
SqlCeCommand selecectnumberscmd = new SqlCeCommand(selectgroup, conn);
reader = selecectnumberscmd.ExecuteReader();
int i = 1;
while (reader.Read())
{
xlWorkSheet.Cells[i, namecol].Value2 = reader.GetString(1);
xlWorkSheet.Cells[i, cellcol].Value2 = reader.GetInt64(2);
xlWorkSheet.Cells[i, emailcol].Value2 = reader.GetString(3); ;
xlWorkSheet.Cells[i, citycol].Value2 = reader.GetString(4);
xlWorkSheet.Cells[i, categorycol].Value2 = reader.GetString(5);
i++;
}
conn.Close();
xlWorkBook.Close(true, misValue, misValue);
xlApp1.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp1);
this.Invoke((MethodInvoker)delegate
{
this.ExportFilepictureBox.Image = null;
labelexpoertolx.Text = "";
});
}
catch (Exception e13)
{
MessageBox.Show("Error Exporting data" + e13.Message);
conn.Close();
}
Cursor.Current = Cursors.Default;
and
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();
}
}
If you are dead set on using interop then it is best to first create an array of values then write it out in one foul swoop rather than cycling through rows - interop is notoriously slow at this
Personally, I'd recommend ditching interop and using an open xml library such as EPPlus for this type of task. I find it easier to use and generally much more performant. As a bonus it gets rid of all that irksome messy releasing com object marshal stuff ;-)
This would replace everything inside your try block with something like this:
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("Data");
ws.Cells[1, namecol].Value = "Name";
ws.Cells[1, cellcol].Value = "Cell No";
ws.Cells[1, emailcol].Value = "Email";
ws.Cells[1, citycol].Value = "City";
ws.Cells[1, categorycol].Value = "Category";
SqlCeDataReader reader = null;
conn.Open(); //open the connection
SqlCeCommand selecectnumberscmd = new SqlCeCommand(selectgroup, conn);
reader = selecectnumberscmd.ExecuteReader();
int i = 1;
while (reader.Read())
{
ws.Cells[i, namecol].Value = reader.GetString(1);
ws.Cells[i, cellcol].Value = reader.GetInt64(2);
ws.Cells[i, emailcol].Value = reader.GetString(3); ;
ws.Cells[i, citycol].Value = reader.GetString(4);
ws.Cells[i, categorycol].Value = reader.GetString(5);
i++;
}
conn.Close();
//Now you have options to export the file - just save someplace, get a byte array or get a reference to the output stream etc with some of the following:
package.SaveAs(someFilePathString);
someByteArrayVariable = package.GetAsByteArray();
package.Stream;
}
As an alternative you can use SwiftExcel library (disclaimer: I wrote the library), like EPPlus it does not use interop, but has better performance as streams data directly to the file, which faster and does not have any memory impact on huge batches.
Here is Nuget command to add it to your project:
PM> Install-Package SwiftExcel
And here is how you can use it:
using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
for (var row = 1; row <= 100; row++)
{
for (var col = 1; col <= 10; col++)
{
ew.Write($"row:{row}-col:{col}", col, row);
}
}
}