The following code exports data to a excel file. It creates the file and creates a new sheet.
StringBuilder query = new StringBuilder();
query.Append("SELECT * from dbo.PastAdjs");
SQL.DataTable dtClients = new SQL.DataTable();
using (SqlConnection cn = new SqlConnection(conStr))
{
using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
{
da.Fill(dtClients);
progressBar1.Value = 20;
textBox1.Text = "20%";
}
//Create Excel workbook for export
Excel.Application oXL;
Excel._Workbook workbook;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oXL.Visible = false;
workbook = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)workbook.ActiveSheet;
Excel.Worksheet newWorksheet;
int sheetamt = 4;
for (int t = 1; t < sheetamt + 1; t++)
{
newWorksheet = (Excel.Worksheet)oXL.Worksheets.Add();
}
int count = workbook.Worksheets.Count;
Excel.Worksheet addedSheet = workbook.Worksheets.Add(Type.Missing,
workbook.Worksheets[count], Type.Missing, Type.Missing);
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = null;
worksheet1 = workbook.Sheets[1];
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Worksheet)worksheet1;
worksheet1.Name = "PastAdjs";
DataColumnCollection dcCollection = dtClients.Columns;
for (int i = 1; i < dtClients.Rows.Count + 1; i++)
{
for (int j = 1; j < dtClients.Columns.Count + 1; j++)
{
if (i == 1)
worksheet1.Cells[i, j] = dcCollection[j - 1].ToString();
else
worksheet1.Cells[i, j] = dtClients.Rows[i - 1][j - 1].ToString();
}
}
oXL.ActiveWorkbook.SaveCopyAs(filename);
oXL.ActiveWorkbook.Saved = true;
oXL.Quit();
How can I modify this to save to an existing worksheet in an existing excel file?
Related
I have a datagridview and already have a export function using Microsoft interop however i am struggling to find a solution to the loading the data.
My code to export to Excel:
private void iSave()
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Journal"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from Journal Pro";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
I also want it to add data from the second row as the first row is the title of the columns.
If theres a solution to use excel to load data in using the same format which is exported in i would be grateful :)
I am also open to other methods of saving, it doesn't have to be to an excel file.
I have used some other codes found online such as
`
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files Only | *.xlsx; *.xls";
ofd.Title = "Choose the File";
if (ofd.ShowDialog() == DialogResult.OK)
FileName_LBL.Text = ofd.FileName;
}
Microsoft.Office.Interop.Excel._Application xlapp;
Microsoft.Office.Interop.Excel._Workbook xlworkbook;
Microsoft.Office.Interop.Excel._Worksheet xlworksheet;
Microsoft.Office.Interop.Excel._Worksheet xlrange;
try
{
xlapp = new Microsoft.Office.Interop.Excel.Application();
xlworkbook = xlapp.Workbooks.Open(FileName_LBL.Text);
xlworksheet = xlworkbook.Worksheets["Exported from Journal Pro"];
xlrange = (Microsoft.Office.Interop.Excel._Worksheet)xlworksheet.UsedRange;
dataGridView1.ColumnCount = xlrange.Columns.Count;
for (int xlrow = 2; xlrow <= xlrange.Rows.Count; xlrow++)
{
dataGridView1.Rows.Add(xlrange.Cells[xlrow, 2].Text, xlrange.Cells[xlrow, 3].Text, xlrange.Cells[xlrow, 4].Text, xlrange.Cells[xlrow, 5].Text, xlrange.Cells[xlrow, 6].Text, xlrange.Cells[xlrow, 7].Text);
}
xlworkbook.Close();
xlapp.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
`
but i get errors such as DISP_E_BADINDEX and E_NOINTERFACE
You can use this method to finish loading the data.
Step 1: Convert dataGridView to dataTable.
Step 2: Export dataTable to Excel .
Step 3: button calls the OutputExcel method.
Full Code
private void button1_Click(object sender, EventArgs e)
{
OutputExcel(dataGridView1);
}
public void OutputExcel(DataGridView dataGridView)
{
string filePath = "";
SaveFileDialog s = new SaveFileDialog();
s.Title = "Excel";
s.Filter = "Excel(*.xlsx)|*.xlsx";
s.FilterIndex = 1;
if (s.ShowDialog() == DialogResult.OK)
filePath = s.FileName;
else
return;
//Step 1: Convert dataGridView to dataTable
DataTable tmpDataTable = new DataTable("tmpDataTable");
DataTable modelTable = new DataTable("ModelTable");
for (int column = 0; column < dataGridView.Columns.Count; column++)
{
if (dataGridView.Columns[column].Visible == true)
{
DataColumn tempColumn = new DataColumn(dataGridView.Columns[column].HeaderText, typeof(string));
tmpDataTable.Columns.Add(tempColumn);
DataColumn modelColumn = new DataColumn(dataGridView.Columns[column].Name, typeof(string));
modelTable.Columns.Add(modelColumn);
}
}
for (int row = 0; row < dataGridView.Rows.Count; row++)
{
if (dataGridView.Rows[row].Visible == false)
continue;
DataRow tempRow = tmpDataTable.NewRow();
for (int i = 0; i < tmpDataTable.Columns.Count; i++)
tempRow[i] = dataGridView.Rows[row].Cells[modelTable.Columns[i].ColumnName].Value;
tmpDataTable.Rows.Add(tempRow);
}
if (tmpDataTable == null)
{
return;
}
//Step 2: Export dataTable to Excel
long rowNum = tmpDataTable.Rows.Count;//line
int columnNum = tmpDataTable.Columns.Count;//column
Excel.Application m_xlApp = new Excel.Application();
m_xlApp.DisplayAlerts = false;
m_xlApp.Visible = false;
Excel.Workbooks workbooks = m_xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//Get sheet1
try
{
string[,] datas = new string[rowNum + 1, columnNum];
for (int i = 0; i < columnNum; i++) //Write field
datas[0, i] = tmpDataTable.Columns[i].Caption;
Excel.Range range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
range.Font.Size = 10;
int r = 0;
for (r = 0; r < rowNum; r++)
{
for (int i = 0; i < columnNum; i++)
{
object obj = tmpDataTable.Rows[r][tmpDataTable.Columns[i].ToString()];
datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();
}
Application.DoEvents();
}
Excel.Range fchR = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];
fchR.Value2 = datas;
worksheet.Columns.EntireColumn.AutoFit();
m_xlApp.Visible = false;
range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];
range.Font.Size = 9;
range.RowHeight = 14.25;
range.Borders.LineStyle = 1;
range.HorizontalAlignment = 1;
workbook.Saved = true;
workbook.SaveCopyAs(filePath);
}
catch (Exception ex)
{
MessageBox.Show("Export Exception:" + ex.Message, "Export Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
m_xlApp.Workbooks.Close();
m_xlApp.Workbooks.Application.Quit();
m_xlApp.Application.Quit();
m_xlApp.Quit();
MessageBox.Show("Export successful!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Effect:
Hope it can help you.
I have a DataGridView in WinForms 2.0 C# that is populated from a DataTable (from SQL) and with already created column headers in DataGridView:
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, conn.ConnectionString);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
tableMainGrid = new DataTable();
dAdapter.Fill(tableMainGrid);
...
dataGridView1.DataSource = tableMainGrid;
dataGridView1.AutoGenerateColumns = false;
The problem is, when I use the following command:
worksheet.ImportDataGridView(dgv, 1, 1,true,false);
I get the header from the SQL command / DataTable and not from the Grid.
I use this code to export:
public static void ExportToExcel(DataGridView dgv, string lang, string tablename)
{
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
worksheet.ImportDataGridView(dgv, 1, 1,true,false);
worksheet.AutoFilters.FilterRange = worksheet.Range;
worksheet.Range.AutofitColumns();
worksheet.Range.AutofitRows();
//...more code - styling header and cells
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel XLS|*.xls";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
workbook.SaveAs(saveFileDialog1.FileName, ExcelSaveType.SaveAsXLS);
System.Diagnostics.Process.Start(saveFileDialog1.FileName);
}
}
}
Syncfusion Version : 16.3.0.21
Visual Studio: 2005
Instead of using:
worksheet.ImportDataGridView(dgv, 1, 1,true,false);
OR
worksheet.ImportDataTable(table, true, 1, 1);
I'm using for loops:
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2013;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
for (int i = 1; i < dgv.Columns.Count + 1; i++)
{
worksheet.Range[1, i].Text = dgv.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dgv.Rows.Count; i++)
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
worksheet.Range[i + 2, j + 1].Text = dgv.Rows[i].Cells[j].Value.ToString();
}
}
worksheet.AutoFilters.FilterRange = worksheet.Range;
worksheet.Range.AutofitColumns();
worksheet.Range.AutofitRows();
worksheet.Range.IgnoreErrorOptions = ExcelIgnoreError.All;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel XLS|*.xls";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
workbook.SaveAs(saveFileDialog1.FileName, ExcelSaveType.SaveAsXLS);
System.Diagnostics.Process.Start(saveFileDialog1.FileName);
}
}
this way I get the header and also all the rows
#jdweng and #housheng: thanks for the help
What is the reason I am getting the error like in datagridview below?
System.InvalidCastException: The COM object of type '' Microsoft.Office.Interop.Excel.ApplicationClass' could not be assigned to interface type 'Microsoft.Office.Interop.Excel._Application'. This operation failed because the QueryInterface call in the COM component for the interface with the IID '{000208D5-0000-0000-C000-000000000046}' failed with the following error: Error loading type library / DLL. (HRESULT exception returned: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)). '
The code I wrote is:
saveFileDialog.InitialDirectory = "C:";
saveFileDialog.Title = "Save as Excel File";
saveFileDialog.FileName = "Data";
saveFileDialog.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if (saveFileDialog.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Application.Workbooks.Add(Type.Missing);
excelApp.Columns.ColumnWidth = 20;
for (int i = 1; i < dgwReport.Columns.Count + 1; i++)
{
excelApp.Cells[1, i] = dgwReport.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dgwReport.Rows.Count; i++)
{
for (int j = 0; j < dgwReport.Columns.Count; j++)
{
excelApp.Cells[i + 2, j + 1] = dgwReport.Rows[i].Cells[j].Value;
}
}
excelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog.FileName.ToString());
excelApp.ActiveWorkbook.Saved = true;
excelApp.Quit();
}
Using the posted code, I did not get the error you describe…
excelApp.Application.Workbooks.Add(Type.Missing);
This appears correct in creating a new Workbook. However, when it comes to writing the data to the workbook it appears to have a problem. The problem is that the code is writing the data to the excelApp and this is incorrect. The excelApp could have numerous workbooks open and each workbook could have numerous “worksheets.” You need to specify “where” (which worksheet in which workbook) you want to write to.
Since you are creating a new workbook, you need to “add” a new worksheet and write to that worksheet instead of the excelApp.
I tested the code below and it writes the data properly to a new worksheet in a new workbook.
saveFileDialog.InitialDirectory = "C:";
saveFileDialog.Title = "Save as Excel File";
saveFileDialog.FileName = "Data";
saveFileDialog.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
try {
if (saveFileDialog.ShowDialog() != DialogResult.Cancel) {
excelApp = new Microsoft.Office.Interop.Excel.Application();
workbook = excelApp.Application.Workbooks.Add(Type.Missing);
worksheet = workbook.ActiveSheet;
excelApp.Columns.ColumnWidth = 20;
for (int i = 1; i < dgwReport.Columns.Count + 1; i++) {
worksheet.Cells[1, i] = dgwReport.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dgwReport.Rows.Count; i++) {
for (int j = 0; j < dgwReport.Columns.Count; j++) {
worksheet.Cells[i + 2, j + 1] = dgwReport.Rows[i].Cells[j].Value;
}
}
excelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog.FileName.ToString());
excelApp.ActiveWorkbook.Saved = true;
workbook.Close();
excelApp.Quit();
}
}
catch (Exception ex) {
MessageBox.Show("Excel write error: " + ex.Message);
}
finally {
// release the excel objects to prevent leaking the unused resource
if (worksheet != null)
Marshal.ReleaseComObject(worksheet);
if (workbook != null)
Marshal.ReleaseComObject(workbook);
if (excelApp != null)
Marshal.ReleaseComObject(excelApp);
}
I'm generating an excel file in C# and excel file is format is as follows.
And Columns From C1 will be dynamic since there can be several dates.
And what I need to do is only allow editing for rows with Ctype
YYY
Is there any way to identify rows with Ctype = YYY
The code I use to generate excel is as follows
public string ExcelGenerator()
{
DataTable dt = GetDataTable();
var fileName = "ExcelFile";
var excelApp = new Application();
var workbooks = excelApp.Workbooks;
var excelWorkBook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
var sheets = excelWorkBook.Sheets;
var excelWorkSheet = sheets[1];
excelWorkSheet.Name = "ExcelFile";
int iCol = 1;
// Add column headings...
foreach (DataColumn c in dt.Columns)
{
excelWorkSheet.Cells[1, iCol] = c.ColumnName; ;
((Range)excelWorkSheet.Cells[1, iCol]).Interior.Color = ColorTranslator.ToOle(Color.DarkGray);
iCol++;
}
// for each row of data...
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = dt.Rows[j].ItemArray[k].ToString();
}
}
string fullpath = Path.Combine(excelPath, fileName);
if (File.Exists(fullpath))
{
try
{
File.Delete(fullpath);
}
catch (IOException e)
{
Console.Write(e.Message);
}
}
excelApp.DisplayAlerts = false;
excelWorkBook.SaveAs(fullpath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
excelWorkBook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelWorkSheet);
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(excelWorkBook);
Marshal.ReleaseComObject(excelApp);
excelWorkSheet = null;
excelWorkBook = null;
excelApp = null;
workbooks = null;
GC.WaitForPendingFinalizers();
GC.Collect();
return fileName;
}
Excel.Office.Interop don't allow range unprotection by programmatically.
For more information, you may visit this website.
https://msdn.microsoft.com/en-us/library/dkcs53f3.aspx
But if you use EPPlus library, you can do like Excel users.
if you allow selective editable column, excel requires sheet protection = true and some unprotected range.
(using EPPlus)
excelWorkSheet.Protection.IsProtected = true;
excelWorkSheet.ProtectedRanges.Add("editable", new ExcelAddress("B"));
hi i exported gridview data into excel but unfortunately the data inside the exported file was different,supposed to be a datatable.
Below is my script in export button, can you tell me what is wrong in my script. I am new in ASP.net thanks
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
//Write Headers
for (j = 0; j < GridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value = GridView1.Columns[j].HeaderText;
}
StartRow++;
//Write datagridview content
for (i = 0; i < GridView1.Rows.Count; i++)
{
for (j = 0; j < GridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = GridView1.Rows[i].Cells[j].Text + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
}
catch
{
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
// "alertMessage",
// "alert(ex.ToString());", true);
}
You can export datagridview data to an excel using the below method:
public void ExportToExcel(DataGridView dgv)
{
try
{
dgv.SelectAll();
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
DataObject doj = dgv.GetClipboardContent();
Clipboard.SetDataObject(doj);
dgv.ClearSelection();
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 2];
Range cell2 = exws.Cells[dgv.Rows.Count + 1, dgv.ColumnCount + 1];
Range cell3 = exws.Cells[1, dgv.ColumnCount + 1];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This method copies all data in the datagridview & pastes it in an excel.You ofcourse need to add a reference to Microsoft.Office.Interop.Excel.
Alternately if you wish to export a datatable to excel you can try below method:
public void ExporttoExcel(System.Data.DataTable dtbl)
{
StringBuilder Output = new StringBuilder();
//The first "line" will be the Headers.
for (int i = 0; i < dtbl.Columns.Count; i++)
{
Output.Append(dtbl.Columns[i].ColumnName + "\t");
}
Output.Append("\n");
//Generate Cell Value Data
foreach (DataRow Row in dtbl.Rows)
{
if (Row.RowState != DataRowState.Deleted)
{
for (int i = 0; i < Row.ItemArray.Length; i++)
{
//Handling the last cell of the line.
if (i == (Row.ItemArray.Length - 1))
{
Output.Append(Row.ItemArray[i].ToString() + "\n");
}
else
{
Output.Append(Row.ItemArray[i].ToString() + "\t");
}
}
}
}
Clipboard.SetText(Output.ToString());
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 1];
Range cell2 = exws.Cells[dtbl.Rows.Count, dtbl.Columns.Count];
Range cell3 = exws.Cells[1, dtbl.Columns.Count];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
Please check if these methods help.
use Text.Replace(" ", "")
myRange.Value2 = GridView1.Rows[i].Cells[j].Text.Replace(" ", "") + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
in markup
<asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/>
I suspect your GridView Bind fails. Below is the method which you can try.
private void ExportToExcel()
{
//First fetch all records from grid to dataset
DataSet dset = new DataSet();
dset.Tables.Add();
//First Add Columns from gridview to excel
for (int i = 0; i < gridView.Columns.Count; i++) //GridView is id of gridview
{
dset.Tables[0].Columns.Add(gridView.Columns[i].HeaderText);
}
//add rows to the table
System.Data.DataRow dr1;
for (int i = 0; i < gridView.Rows.Count; i++)
{
dr1 = dset.Tables[0].NewRow(); //For Example There are only 3 columns into gridview
System.Web.UI.WebControls.Label lblCCName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblCCName");
System.Web.UI.WebControls.Label lblItemName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemName");
System.Web.UI.WebControls.Label lblItemCode =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemCode");
dr1[0] = lblCCName.Text.ToString();
dr1[1] = lblItemName.Text.ToString();
dr1[2] = lblItemCode.Text.ToString();
dset.Tables[0].Rows.Add(dr1);
}
//below code is export dset to excel
ApplicationClass excel = new ApplicationClass();
Workbook wBook;
Worksheet wSheet;
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value);
wSheet = (Worksheet)wBook.ActiveSheet;
System.Data.DataTable dt = dset.Tables[0];
System.Data.DataColumn dc = new DataColumn();
int colIndex = 0;
int rowIndex = 4;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[5, colIndex] = dcol.ColumnName;
}
foreach (DataRow drow in dt.Rows)
{
rowIndex = rowIndex + 1;
colIndex = 0;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[rowIndex + 1, colIndex] = drow[dcol.ColumnName];
}
}
wSheet.Columns.AutoFit();
// Server File Path Where you want to save excel file.
String strFileName = Server.MapPath("~\\Images\\StockStatement.xls");
Boolean blnFileOpen = false;
try
{
System.IO.FileStream fileTemp = File.OpenWrite(strFileName);
fileTemp.Close();
}
catch
{
blnFileOpen = false;
}
if (System.IO.File.Exists(strFileName))
//It checks if file exists then it delete that file.
{
System.IO.File.Delete(strFileName);
}
}
In the Button_Click() event, call this function.
Hi this is were i came up after long journey, i used the Aspose method on Exporting Gridview in Excel, it's simple yet so powerfull! hope this will help,
Code behind Export_button:
//Instantiate a new workbook
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
//Get the first worksheet in the workbook
Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
//Import data from GridView control to fill the worksheet
worksheet.Cells.ImportGridView(GridView1, 0, 0, new Aspose.Cells.ImportTableOptions() { IsFieldNameShown = true });
worksheet.AutoFitColumns();
//Send result to client in XLS format
workbook.Save(this.Response, "export.xls", ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions());