Related
private void btn_gnrt_files_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
//reading text file
FileInfo theSourceFile = new FileInfo(#"" + textBox1.Text);
StreamReader reader = theSourceFile.OpenText();
String filename = "";
String text = "";
do
{
text = reader.ReadLine();
if (text != null)
{
//MessageBox.Show(""+state);
String[] fname = text.Split('|'); //writiting file
if (state == true)
{
filename = fname[1];
filename.TrimStart();
//MessageBox.Show(filename);
Excel.Application excel = new Excel.Application();
excel.Visible = true;
//true is append parameter
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
writer.WriteLine(text.Replace("|", ","));
I get excel files with data through this code. but i cant
put column headers to excel sheets. plz tell me how to add these headers
<<reg no,br no,pr no,curency>>
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
System.Windows.MessageBox.Show("Excel is not properly installed!!");
return;
}
xlWorkBook = xlApp.Workbooks.Add();
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "reg no";
xlWorkSheet.Cells[1, 2] = "br no"
xlWorkSheet.Cells[1, 3] = "pr no"
xlWorkSheet.Cells[1, 4] = "curency";
And then do your business...
Column headers are just regular cells in Excel (or CSV), so add them as a first line.
Add that header-line before you start the loop to write the data lines.
I want to write data to an existing Excel file, whilst preserving the original data.
The file has sheet1; I want to write on sheet2, then save.
The problem is that every time I save, it will create a new Excel file and overwrite the existing one.
Could anyone provide any help to keep the old data while saving?
I have the following function
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 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);
MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());
xlWorkBook.Close(true, misValue, misValue);
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();
}
}
}
}
This is my way to add data to existing excel file: (Its very simple and efficient)
1 - Add Microsoft.Office.Interop.Excel component as a reference to your application
You can find it in .Net FrameWork in Extensions section
2- then add:
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
3- Now I have a simple class with 3 methods (openExcel, addDataToExcel, closeExcel)
public class ExcelFile
{
private string excelFilePath = string.Empty;
private int rowNumber = 1; // define first row number to enter data in excel
Excel.Application myExcelApplication;
Excel.Workbook myExcelWorkbook;
Excel.Worksheet myExcelWorkSheet;
public string ExcelFilePath
{
get { return excelFilePath; }
set { excelFilePath = value; }
}
public int Rownumber
{
get { return rowNumber; }
set { rowNumber = value; }
}
public void openExcel()
{
myExcelApplication = null;
myExcelApplication = new Excel.Application(); // create Excell App
myExcelApplication.DisplayAlerts = false; // turn off alerts
myExcelWorkbook = (Excel.Workbook)(myExcelApplication.Workbooks._Open(excelFilePath, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value)); // open the existing excel file
int numberOfWorkbooks = myExcelApplication.Workbooks.Count; // get number of workbooks (optional)
myExcelWorkSheet = (Excel.Worksheet)myExcelWorkbook.Worksheets[1]; // define in which worksheet, do you want to add data
myExcelWorkSheet.Name = "WorkSheet 1"; // define a name for the worksheet (optinal)
int numberOfSheets = myExcelWorkbook.Worksheets.Count; // get number of worksheets (optional)
}
public void addDataToExcel(string firstname, string lastname, string language, string email, string company)
{
myExcelWorkSheet.Cells[rowNumber, "H"] = firstname;
myExcelWorkSheet.Cells[rowNumber, "J"] = lastname;
myExcelWorkSheet.Cells[rowNumber, "Q"] = language;
myExcelWorkSheet.Cells[rowNumber, "BH"] = email;
myExcelWorkSheet.Cells[rowNumber, "CH"] = company;
rowNumber++; // if you put this method inside a loop, you should increase rownumber by one or wat ever is your logic
}
public void closeExcel()
{
try
{
myExcelWorkbook.SaveAs(excelFilePath, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange,
System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value); // Save data in excel
myExcelWorkbook.Close(true, excelFilePath, System.Reflection.Missing.Value); // close the worksheet
}
finally
{
if (myExcelApplication != null)
{
myExcelApplication.Quit(); // close the excel application
}
}
}
}
According to Programmatically Insert to Existing Excel File using C# by R Manimaran:
Here is the code which will do the insertion in an already exists excel file.
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public static void ReadExistingExcel()
{
string path = #"C:\Tool\Reports1.xls";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount= range.Rows.Count;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
}
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
If you need to create a new Sheet use the following code.
oSheet = (Excel.Worksheet)oWB.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
oSheet.Name = SheetName;
Use ClosedXml dll in my case its resolved my problem
var workbook = new XLWorkbook(fileName);
var ws1 = workbook.Worksheet(1);
var ws2 = workbook.Worksheet(2);
workBook.SaveAs(fileName);
Here is my code:
public void ExcelDataAssign(List<string> ColumnwiseData, int length, DateTime ReportDate, List<string> AmountList, List<string> PeriodDateList, int CellId)
{
int PeriodColIndex = 6, Desc1ColIndex = 14, Desc2ColIndex = 11, Desc3ColIndex = 9, PeriodDateColIndex = 7;
int PeriodRowIndex = 3, Desc1RowIndex = 1, Desc2RowIndex = 1, Desc3RowIndex = 1, PeriodDateRowIndex = 3;
string cellName = ColumnwiseData[length];
string CapitiveName = ColumnwiseData[2 * length];
string DomicileName = ColumnwiseData[3 * length];
string file = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + #"\Excel\OutputTemplate.xlsx";
string fileName = file.Replace("bin", "").Replace("Debug", "");
var workbook = new XLWorkbook(fileName);
var ws1 = workbook.Worksheet(1);
ws1.Cell(1, 2).Value = DomicileName;
ws1.Cell(2, 2).Value = CapitiveName;
ws1.Cell(3, 2).Value = cellName;
ws1.Cell(4, 2).Value = ReportDate;
int amntIncr = 0;
while (AmountList.Count > amntIncr)
{
ws1.Cell(PeriodColIndex, PeriodRowIndex).Value = "Period";
ws1.Cell(Desc1ColIndex, Desc1RowIndex + 2).Value = AmountList[amntIncr];
ws1.Cell(Desc2ColIndex, Desc2RowIndex + 2).Value = (AmountList[amntIncr + 1]);
ws1.Cell(Desc3ColIndex, Desc3RowIndex + 2).Value = (AmountList[amntIncr + 2]);
PeriodRowIndex++;
Desc1RowIndex++;
Desc2RowIndex++;
Desc3RowIndex++;
amntIncr = amntIncr + 3;
}
int periodDateIncr = 0;
while (PeriodDateList.Count > periodDateIncr)
{
ws1.Cell(PeriodDateColIndex, PeriodDateRowIndex).Value = PeriodDateList[periodDateIncr];
PeriodDateRowIndex++;
periodDateIncr = periodDateIncr + 3;
}
var ws2 = workbook.Worksheet(2);
ws2.Cell(1, 2).Value = DomicileName;
ws2.Cell(2, 2).Value = CapitiveName;
ws2.Cell(3, 2).Value = cellName;
ws2.Cell(4, 2).Value = ReportDate;
SqlParameter paramCellId = new SqlParameter("#CellId", CellId);
SqlParameter paramReportDate = new SqlParameter("#ReportDate", ReportDate);
DataTable dt = new DataTable();
var data = SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Usp_inputResult", paramCellId, paramReportDate).Tables[0];
List<string> lstClmwiseData = new List<string>();
foreach (DataRow r in data.Rows)
{
foreach (DataColumn c in data.Columns)
{
lstClmwiseData.Add(r[c].ToString());
}
}
int snoColIndex = 6, GLCodeColIndex = 6, DescriptioColIndex = 6, movementDebitColIndex = 6, movementCreditColIndex = 6, ClosingdebitcolIndex = 6, ClosingCreditColIndex = 6;
int snoRowIndex = 1, GLCodRowIndex = 2, DescriptioRowIndex = 3, movementDebitRowIndex = 4, movementCreditRowIndex = 5, ClosingdebitRowIndex = 6, ClosingCreditRowIndex = 7;
int secondSheet = 0;
int SnoIncrement = 1;
while (lstClmwiseData.Count > secondSheet)
{
ws2.Cell(snoColIndex, snoRowIndex).Value = SnoIncrement;
ws2.Cell(GLCodeColIndex, GLCodRowIndex).Value = lstClmwiseData[secondSheet];
ws2.Cell(DescriptioColIndex, DescriptioRowIndex).Value = lstClmwiseData[secondSheet + 1];
ws2.Cell(movementDebitColIndex, movementDebitRowIndex).Value = lstClmwiseData[secondSheet + 2];
ws2.Cell(movementCreditColIndex, movementCreditRowIndex).Value = lstClmwiseData[secondSheet + 3];
ws2.Cell(ClosingdebitcolIndex, ClosingdebitRowIndex).Value = lstClmwiseData[secondSheet + 4];
ws2.Cell(ClosingCreditColIndex, ClosingCreditRowIndex).Value = lstClmwiseData[secondSheet + 5];
snoColIndex++;
GLCodeColIndex++;
DescriptioColIndex++;
movementDebitColIndex++;
movementCreditColIndex++;
ClosingdebitcolIndex++;
ClosingCreditColIndex++;
SnoIncrement++;
secondSheet = secondSheet + 6;
}
string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + #"\Downloads\ReportUtitlity";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string FileName = workbook.Author + "_" + "Report_"+CellId+ "CellId" +"_" + $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}";
workbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + #"\Downloads\ReportUtitlity\" + FileName + ".xlsx");
}
Here i am exporting the datatables in a dataset to excel.How to make the header font of the datatable alone look bold.Here is my code
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
foreach (DataTable table in dtInputParameters.Tables)
{
dataExportExcel.DataSource = table;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
htmlWrite.WriteLine("<br/>");
// htmlWrite.AddStyleAttribute(System.Web.UI.HtmlTextWriterStyle.FontWeight, "bold");
}
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + worksheetName + "</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sbResponseString.Append(stringWriter + "<table width='800' height='100' align='center' style='text-align:center'");
sbResponseString.Append("</table></body></html>");
HttpContext.Current.Response.Write(sbResponseString.ToString());
HttpContext.Current.Response.End();
Any suggestion?
You need to set the HeaderStyle on the DataGrid to use bold font. That's all.
dataExportExcel.HeaderStyle.Font.Bold=true;
Cursor.Current = Cursors.WaitCursor;
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "Total Expiry Inventories Data ";
sfd.DefaultExt = "xls";
sfd.Filter = "xlsx files(*.xlsx)|*.xlsx";
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook workbook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook.Worksheets[1];
worksheet1.Name = "Expiry Data";
for (int i = 1; i < GrdViewData.Columns.Count + 1; i++)
{
worksheet1.Cells[1, i] = GrdViewData.Columns[i - 1].HeaderText;
worksheet1.Cells[1, i].Font.Bold = true;
}
for (int i = 0; i < GrdViewData.Rows.Count; i++)
{
for (int j = 0; j < GrdViewData.Columns.Count; j++)
{
worksheet1.Cells[i + 2, j + 1] = GrdViewData.Rows[i].Cells[j].Value.ToString();
}
}
worksheet1.Rows.Font.Size = 12;
// Excel.Range range_Consolidated = worksheet1.Rows.get_Range("a1", "d1");
// range_Consolidated.Font.Bold = true;
// range_Consolidated.Font.Italic = true;
string ExcelFileName = sfd.FileName;
workbook.SaveAs(ExcelFileName);
workbook.Close(false, ExcelFileName, Missing.Value);
ExcelApp.Quit();
ExcelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("File Saved! you can open it from\n '" + sfd.FileName + "'", "EXPORT", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
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 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();
}