I have a form that allows user to select item from a list on a grid and allows them to export the data corresponding to the selected items. The data should be exported to the existing excel template. I tried some codes but what happens is when the downloaded excel file is opened it just shows blank. Can you please help me why it happens and what's wrong with my code.
Below is my code: Thanks in advance
try
{
UpdateDataSelection();
string pFileName = "SubconOneLineList_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
string pSubConCodeLists = string.Empty;
string pJobCodeKey = string.Empty;
string pCountryCode = string.Empty;
string pWorkCategoryCode = string.Empty;
string pCapacityCode = string.Empty;
string pOperativeCountryCode = string.Empty;
string pNameAbbr = string.Empty;
string pAffiliates = string.Empty;
pSubConCodeLists = string.Join(",", DataSelection);
if (pSubConCodeLists == string.Empty)
{
GetSubconDatabaseFilter(out pSubConCodeLists, out pNameAbbr, out pJobCodeKey, out pCountryCode, out pOperativeCountryCode, out pWorkCategoryCode, out pAffiliates, out pCapacityCode);
}
string pGridFilter = (rgvSubcontractor.MasterTableView.FilterExpression == null ? string.Empty : rgvSubcontractor.MasterTableView.FilterExpression);
string pSortString = "";
if (rgvSubcontractor.MasterTableView.SortExpressions != null)
{
pSortString = ((rgvSubcontractor.MasterTableView.SortExpressions.GetSortString() == null) || (rgvSubcontractor.MasterTableView.SortExpressions.GetSortString() == string.Empty) ? pSortString : rgvSubcontractor.MasterTableView.SortExpressions.GetSortString());
}
pSortString = (pSortString == string.Empty ? "COMPANY_NAME ASC" : pSortString + ", COMPANY_NAME ASC");
DataTable pDTSubconOneLineList = mSubContractorBS.getRptSubContractorOneLineList(pSubConCodeLists, pNameAbbr, string.Empty, string.Empty, pJobCodeKey, pCountryCode, pOperativeCountryCode, pWorkCategoryCode, pAffiliates, pCapacityCode);
DataView pDVSubconOneLineList = new DataView(pDTSubconOneLineList);
if (pGridFilter != string.Empty)
{
pDVSubconOneLineList.RowFilter = pGridFilter;
}
pDVSubconOneLineList.Sort = pSortString;
pDTSubconOneLineList = pDVSubconOneLineList.ToTable();
pDTSubconOneLineList.TableName = "USP_RPT_SUBCON_ONE_LINE_LIST";
Process[] processList = Process.GetProcesses();
string path = Server.MapPath("~") + "\\SIS\\Template\\Download\\Subcon_Profile_List_Import_Template.xlsx";
//string targetPath = Convert.ToString(Session["App_Data_Path"]) + "EXPORT_OUTPUT";
string targetPath = Convert.ToString(Server.MapPath("~")) + "EXPORT_OUTPUT";
string destFile = System.IO.Path.Combine(targetPath, pFileName);
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
File.Copy(path, destFile, true);
object misValue = System.Reflection.Missing.Value;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(destFile, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet.get_Range("A2", "AN" + xlWorkSheet.Rows.Count.ToString()).Clear();
object[,] objData = null;
int rowcount = pDTSubconOneLineList.Rows.Count;
objData = new Object[pDTSubconOneLineList.Rows.Count, pDTSubconOneLineList.Columns.Count];
for (int row = 0; row < pDTSubconOneLineList.Rows.Count; row++)
{
for(int column= 0; column < pDTSubconOneLineList.Columns.Count; column++)
{
objData[row, column] = pDTSubconOneLineList.Rows[row][column].ToString();
}
}
((Excel.Worksheet)xlWorkBook.Sheets[1]).Select(Type.Missing);
xlWorkBook.Save();
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;
GC.Collect();
string pMimeType = string.Empty;
string pEncoding = string.Empty;
string pExtension = string.Empty;
Response.Buffer = true;
Response.Clear();
Response.AppendCookie(new HttpCookie("fileDownloadToken", hdDownLoadToken.Value));
Response.ContentType = pMimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + pFileName);
Response.Flush();
}
catch (Exception ex)
{
ErrorHelper.HandleError(ex);
}
You are not actually writing the data to the Sheet.
After your for loop filling objData, try:
Excel.Range targetRange = xlWorkSheet.get_Range("A2", "AN" + xlWorkSheet.Rows.Count.ToString());
targetRange.Value = objData;
i am working on excel import to grid view using DataTable in c#, but my problem is its working fine on my local system but its redirecting to login page on my online server and i have tried both Microsoft.Office.Interop.Excel & OLEdb connection. but the problem is same. please tell me what is the problem with these or any one have any other function to import Excel data in GridView.
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Have a look:
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
It is better not using MS Office interop in server cases which will bring a lot of performance and memory issues in the future. Recommend using some 3rd party library, for example: https://www.nuget.org/packages/Spread.Services/ to get what you wanted.
inside my class i am declaring
public Excel.Range range { get; set; }
the constructor of the class calls this method:
private void OpenWorkBook()
{
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
}
after that when i reference range from a different method:
public void CreateFiles(string column)
{
try
{
var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
var deleteRange = range;
i am getting:
valueRange threw an exception of type System.Runtime.InteropServices.InvalidComObjectException'
does anyone know why i am losing the contents of this variable?
here's my full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace EmailSalesVolumeSolution
{
class WorkBook
{
public string MasterFileName { get; set; }
public string[] DistinctEmails { get; set; }
public Excel.Application xlApp {get;set;}
public Excel.Workbook xlWorkBook { get; set; }
public Excel.Worksheet xlWorkSheet { get; set; }
public Excel.Range range { get; set; }
private void OpenWorkBook()
{
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(MasterFileName, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
}
public WorkBook(string filename)
{
MasterFileName = filename;
//xlWorkBook = null;
//xlApp = null;
//xlWorkSheet = null;
//range = null;
OpenWorkBook();
}
public void SendEmail()
{
}
public void CreateFiles(string column)
{
try
{
var valueRange = range.get_Range(column + "3", column + range.Rows.Count.ToString());
var deleteRange = range;
string cell = "";
DistinctEmails = DistinctValues(valueRange);
foreach (string email in DistinctEmails)
{
for (int rCnt = 2; rCnt <= valueRange.Rows.Count; rCnt++)
{
cell = (string)(valueRange.Cells[rCnt, 1] as Excel.Range).Value2;
if (cell == null || cell != email)
{
deleteRange=xlWorkSheet.get_Range(column + rCnt.ToString() + ":" + column + rCnt.ToString(), Type.Missing);
deleteRange.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
}
}
xlWorkBook.SaveAs(xlWorkBook.Path + #"\" + email, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
//DisposeMe();
// Release all COM RCWs.
// The "releaseObject" will just "do nothing" if null is passed,
// so no need to check to find out which need to be released.
// The "finally" is run in all cases, even if there was an exception
// in the "try".
// Note: passing "by ref" so afterwords "xlWorkSheet" will
// evaluate to null. See "releaseObject".
releaseObject( xlWorkSheet);
releaseObject( xlWorkBook);
// The Quit is done in the finally because we always
// want to quit. It is no different than releasing RCWs.
if (xlApp != null)
{
xlApp.Quit();
}
releaseObject( xlApp);
}
}
private string[] DistinctValues(Excel.Range EmailList)
{
string cell = "";
List<string> emails = new List<string>();
for (int rCnt = 1; rCnt <= EmailList.Rows.Count; rCnt++)
{
cell = (string)(EmailList.Cells[ rCnt,1] as Excel.Range).Value2;
if (cell!=null)
emails.Add(cell.ToString());
}
releaseObject(EmailList);
return emails.Distinct().ToArray();
}
private void releaseObject( object obj) // note ref!
{
// Do not catch an exception from this.
// You may want to remove these guards depending on
// what you think the semantics should be.
if (obj != null && Marshal.IsComObject(obj))
{
Marshal.ReleaseComObject(obj);
}
// Since passed "by ref" this assingment will be useful
// (It was not useful in the original, and neither was the
// GC.Collect.)
obj = null;
}
private void DisposeMe()
{
// Cleanup:
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkBook.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkBook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
}
}
}
here's how i instantiate the class!!
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
InitializeWorkBook(openFileDialog1.FileName);
}
private void InitializeWorkBook(string filename)
{
WorkBook wb= new WorkBook(filename);
wb.CreateFiles("A");
}
I've written this code to count the number of rows that are populated in an excel worksheet. It works until it gets yo a certain number of rows (not the total). Then comes up with the error message "Exception from HRESULT: 0x800A01A8" Any help much appreciated
namespace ConsoleApplication1
{
class ExcelClass
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Excel.Application excelApp = new Excel.Application(); // Creates a new Excel Application
excelApp.Visible = true; // Makes Excel visible to the user.
// The following code opens an existing workbook
string workbookPath = "D:\\RSG_D.xls"; // Add your own path here
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
// The following gets the Worksheets collection
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
// The following gets Sheet1 for editing
string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
//void SetNewCurrentCulture()
//{
oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//}
int rowCounter = 1;
while ( rowCounter != null)
{
Excel.Range countRows = (Excel.Range)excelWorksheet.Cells[rowCounter, 1] as Excel.Range;
object CountRows = countRows.Value;
rowCounter++;
Console.WriteLine(CountRows);
}
excelWorkbook.Close(0);
excelApp.Quit();
//reset Current Culture back to the originale
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}
}
}
I had the exact same problem tonight: Here is the code I have used and it's worked properly for me:
Excel.Application oExcel = new Excel.Application();
//oExcel.Visible = true; (this caused me huge problems
Excel.Workbook oBook = oExcel.Workbooks.Open(#"C:\Yoink\Birr Castle Demesne Interactive Map\Birr Castle Demesne Interactive Map\bin\Debug\Red Tree Trail.xlsx");
Excel.Worksheet oSheet1 = oBook.Worksheets["Red Tree Trail"] as Excel.Worksheet; (use your own worksheet title there)
Excel.Range rng = oSheet1.get_Range("A1", "AJ51"); (use your own range there
int rowCount = rng.Rows.Count;
int colCount = rng.Columns.Count;
string[,] tsReqs = new string[rowCount, colCount];
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
string str = rng.Cells[i, j].Text;
tsReqs[i - 1, j - 1] = str;
}
}
I think your problem is in this line:
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0,
false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
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();
}