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());
Related
I'll show the excel output in order to be easy to understand
Excel output
The code is also very simple, how can I make the rows correct? I tried creating multiple datatables and merging them, but the merge is always vertical so I was getting the same output.
dt.Columns.Add("Nomes", typeof(string));
DataRow dr;
for (int i = 0; i < surveyAnswers.Respostas.Count; i++) {
if (i == 0) {
dr = dt.NewRow();
dr[0] = surveyAnswers.Respostas[i].quemRespondeu;
dt.Rows.Add(dr);
}
if (i > 0) {
string nome = surveyAnswers.Respostas[i].quemRespondeu;
if (nome != surveyAnswers.Respostas[i - 1].quemRespondeu) {
dt.Rows.Add(nome);
}
}
}
for (int j = 0; j < surveyGroups.Count; j++) {
string grupo = surveyGroups[j].SubTitulo;
dt.Columns.Add(grupo, typeof(string));
for (int i = 0; i < surveyAnswers.Respostas.Count; i++) {
if (surveyAnswers.Respostas[i].QuestaoGrupo == j) {
dr = dt.NewRow();
dr[j] = surveyAnswers.Respostas[i].QuestaoPergunta;
dt.Rows.Add(dr);
}
}
}
Dictionary<string, string> header = new Dictionary<string, string>();
header.Add("Content-Disposition", "attachment;filename=questionario_resultados.csv");
ResponseUtil.Write(context, DataTableToCSV.WriteToString(dt, true, false), "text/csv; charset=UTF-8", header); ```
You are creating new rows everytime you add a new column in the second for loop, when you created already the rows in the first one. Instead of creating a new row, you should modify the existing rows.
instead of this:
dr = dt.NewRow();
dr[j] = surveyAnswers.Respostas[i].QuestaoPergunta;
dt.Rows.Add(dr);
Try with something like this:
dr[i][grupo] = surveyAnswers.Respostas[i].QuestaoPergunta;
I didn't test it.
Since I don't know how do you get the excel file, I make a change to the excel to make it normal.
I create a winform app and used the datagridview to show the datatable.
private void button1_Click(object sender, EventArgs e)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Open("E:\\test.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
Excel.Range usedRange = worksheet.UsedRange;
int usedrow = usedRange.Rows.Count;
int usedcolumn = usedRange.Columns.Count;
for (int i = 2; i <= usedcolumn; i++)
{
int row = worksheet.UsedRange.Columns[i, Type.Missing].Rows.Count;
int firstrow = Firstusedrow(usedrow, i, worksheet);
Excel.Range copyRange = worksheet.Range[worksheet.Cells[firstrow, i], worksheet.Cells[row, i]];
Excel.Range insertRange = worksheet.Range[worksheet.Cells[2, i], worksheet.Cells[row, i]];
insertRange.Insert(Excel.XlInsertShiftDirection.xlShiftDown, copyRange.Cut());
}
workbook.Save();
workbook.Close();
dataGridView1.DataSource = null;
DataTable table = READExcel("E:\\test.xlsx");
dataGridView1.DataSource = table;
MessageBox.Show("success");
}
public int Firstusedrow(int row,int column, Excel.Worksheet sheet)
{
for (int i = 2; i < row; i++)
{
if ((sheet.Cells[i, column] as Excel.Range).Value2 != null)
{
return i;
}
}
return 0;
}
public DataTable READExcel(string path)
{
Microsoft.Office.Interop.Excel.Application objXL = null;
Microsoft.Office.Interop.Excel.Workbook objWB = null;
objXL = new Microsoft.Office.Interop.Excel.Application();
objWB = objXL.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet objSHT = objWB.Worksheets[1];
int rows = objSHT.UsedRange.Rows.Count;
int cols = objSHT.UsedRange.Columns.Count;
DataTable dt = new DataTable();
int noofrow = 1;
for (int c = 1; c <= cols; c++)
{
string colname = objSHT.Cells[1, c].Text;
dt.Columns.Add(colname);
noofrow = 2;
}
for (int r = noofrow; r <= rows; r++)
{
DataRow dr = dt.NewRow();
for (int c = 1; c <= cols; c++)
{
dr[c - 1] = objSHT.Cells[r, c].Text;
}
dt.Rows.Add(dr);
}
objWB.Close();
objXL.Quit();
return dt;
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable table = READExcel("E:\\test.xlsx");
dataGridView1.DataSource = table;
}
Result;
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"));
I want to make changes to an existing file named "Original" in the directory "C:\Users\Twiga\Documents\VisualStudio2010\Projects\MarkSheetSystem\Original.xls".
Currently, I am only able to save the data that I have exported from my datagridview1 to a new file but that is not my intention.
Below is the code:
private void btnexcel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "Marksheet 1";
worksheet.Cells[12, 1] = dataGridView1.Rows[0].Cells[0].Value.ToString();
int cellRowIndex = 10;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 1; j < dataGridView1.Columns.Count - 1; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 0)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("The marksheet has been saved successfully!");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}
Pertinent to your task, it would be better to export data to Excel Workbook from the DataGridView underlying DataTable (e.g. DataTable _dt = (DataTable)(datagridview1.DataSource)) as shown in the following C# sample code snippet:
/// <summary>
/// export DataTable to Excel (C#)
/// </summary>
internal static void Export2Excel(DataTable dataTable)
{
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application _appExcel = null;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
try
{
// excel app object
_appExcel = new Microsoft.Office.Interop.Excel.Application();
// excel workbook object added
// can be replaced with _appExcel.Workbooks.Open(...)
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
_excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
// column names row (range obj)
Microsoft.Office.Interop.Excel.Range _columnsNameRange;
_columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);
// column names array to be assigned to _columnNameRange
string[] _arrColumnNames = new string[dataTable.Columns.Count];
for (int i = 0; i < dataTable.Columns.Count; i++)
{
// array of column names
_arrColumnNames[i] = dataTable.Columns[i].ColumnName;
}
// assign array to column headers range, make 'em bold
_columnsNameRange.set_Value(misValue, _arrColumnNames);
_columnsNameRange.Font.Bold = true;
// populate data content row by row
for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
{
_excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
dataTable.Rows[Idx].ItemArray;
}
// Autofit all Columns in the range
_columnsNameRange.Columns.EntireColumn.AutoFit();
}
catch { throw; }
}
This will significantly improve the performance by exporting the entire data row at once instead of doing it cell-by-cell.
The only changes you have to make is to replace the line that adds new Workbook:
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
with another one, opening the existing Excel File (e.g. "ExcelFilePath"), like:
_excelWorkbook = _appExcel.Workbooks.Open("ExcelFilePath",
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Hope this may help.
I'm using Excel Interop for C# to export a datagridview to Excel and print it. I'm using this code:
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
int ColumnIndex = 0;
int rowIndex = -1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
rowIndex++;
ColumnIndex = 0;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
ColumnIndex++;
excel.Cells[rowIndex + 1, ColumnIndex] = row.Cells[col.Name].Value;
}
}
excel.Visible = true;
excel.DisplayAlerts = false;
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
worksheet.Activate();
worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 7]].Merge();
worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[2, 7]].Merge();
worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[3, 7]].Merge();
worksheet.Range[worksheet.Cells[4, 1], worksheet.Cells[4, 4]].Merge();
worksheet.Cells[1, 1].Font.Bold = true;
worksheet.Range["A1"].Cells.Font.Size = 15;
worksheet.Range["A4"].Cells.Font.Size = 15;
worksheet.Range["B7"].Cells.Font.Size = 15;
worksheet.Range["B8"].Cells.Font.Size = 15;
worksheet.Range["B9"].Cells.Font.Size = 15;
worksheet.Range["A11"].Cells.Font.Size = 15;
worksheet.Range["B13"].Cells.Font.Size = 15;
worksheet.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
GC.Collect();
GC.WaitForPendingFinalizers();
excel.Quit();
}
catch (Exception ex)
{
MessageBox.Show("Error de exportación.");
}
It works fine, but I need to open an existing file to do this same thing to avoid reconfiguration of the printing margins. I checked other similar questions and tried to apply the "workBook = oXL.Workbooks.Open("path", ...);" but it can make it work. Any thoughts?
To open a file use the open method.
Microsoft.Office.Interop.Excel.Workbooks wkbks = null;
Microsoft.Office.Interop.Excel.Workbook wkbk = null;
wkbks = excel.Workbooks;
wkbk = wkbks.Open(xlsFileName);
At the end of your method you should do a cleanup on all your interop variables:
if (wkbk != null)
{
try
{
wkbk.Close(false);
}
catch
{
}
Marshal.FinalReleaseComObject(wkbk);
wkbk = null;
}
I could export data of datagridview to excel. But the actual format of datagridview was not exported i.e., font, color and space. So, is there any best way to export datagridview to excel i.e. not only data but also the look.
The sample look is this:
Try CSV export
private void ToCsV(DataGridView dGV, string filename)
{
string separator = ",";
StringBuilder stOutput = new StringBuilder();
// Export titles:
StringBuilder sHeaders = new StringBuilder();
for (int j = 0; j < dGV.Columns.Count; j++)
{
sHeaders.Append(dGV.Columns[j].HeaderText);
sHeaders.Append(separator);
}
stOutput.AppendLine(sHeaders.ToString());
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
StringBuilder stLine = new StringBuilder();
for (int j = 0; j < dGV.ColumnCount; j++)
{
stLine.Append(Convert.ToString(dGV[j, i].Value));
stLine.Append(separator);
}
stOutput.AppendLine(stLine.ToString());
}
File.WriteAllText(filename, stOutput.ToString());
}
Before you write code in button_Click event, you must add a reference to the Microsoft.Office.Interop.Excel object library.
Right click on your project and select Add Reference menu. After that go to .NET tab and select and add Microsoft.Office.Interop.Excel.
Write the below code in button_Click event.
// button_Click event
private void button11_Click(object sender, EventArgs e)
{
// creating Excel Application
string fileName = String.Empty;
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
try
{
//Fixed:(Microsoft.Office.Interop.Excel.Worksheet)
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets["Sheet1"];
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Exported from AMIT";
// storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
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();
}
}
// Save The Application
SaveFileDialog saveFileExcel = new SaveFileDialog();
saveFileExcel.Filter = "Excel files |*.xls|All files (*.*)|*.*";
saveFileExcel.FilterIndex = 2;
saveFileExcel.RestoreDirectory = true;
if (saveFileExcel.ShowDialog() == DialogResult.OK)
{
fileName = saveFileExcel.FileName;
//Fixed-old code :11 para->add 1:Type.Missing
workbook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
else
{
return;
// Exit from the application
//app.Quit();
}
}
catch (Exception)
{
//Statement;
}
finally
{
app.Quit();
workbook = null;
app = null;
}
}