Call and export two Gridviews into two separate worksheets - c#

I would like to export gridview1 and gridview2 into two separate worksheets that can be named in my codes as grid view 1 and grid view 2 in one Excel file. I have trouble exporting to Excel and am not sure how to call my export in the button and pass the parameters in to export two Gridviews:
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// 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
worksheet = workbook.Sheets["Sheet" + sheetid];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
// save the application
workbook.SaveAs(#"C:\Users\testacc\Desktop\Test\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
Where do I place the code below?
// creating Excel Application
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);

you will have to create those objects in
public void callingfunction() {
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);
ExportToExcel(app, workbook, gv1, 'sheet1', 1)
ExportToExcel(app, workbook, gv2, 'sheet2', 2)
}

Related

Export Datatable into Excel Strat from Specific Column C#

I have a datatable and I want export the data into excel but start exporting from a specific column. Scenario, I have an excel sheet and first 5 columns [A-E] have data and want to export from datatable and should start from column F.
How to achieve this in C# console application?
So, the most obvious approach here would be to iterate over the data table's rows and write each to the Excel sheet manually:
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
// Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
// Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
// Write the data. Remember that Excel is 1-indexed
int rowIndex = 1;
foreach (DataRow row in table.Rows) {
int colIndex = 6;
foreach (DataColumn col in table.Columns) {
oSheet.Cells[rowIndex, colIndex] = row[col];
colIndex++;
}
rowIndex++;
}
// Save the Excel file
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit Excel
oWB.Close();
oXL.Quit();
There's probably a more elegant solution to this problem but I think this will get the job done, at least. As a reference, my Excel code was modified from this question, so you might be able to find a better match for your specific needs there.
Alternatively, you could try using the ClosedXML library:
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
var sheet = workbook.Worksheets.Add(table);
var firstColumn = sheet.Column(1);
firstColumn.InsertColumnsBefore(5);
This code works by creating a new Excel worksheet from the datatable, getting a pointer to the first column in the worksheet and then inserting five columns (A - E) before it.
you can use ClosedXML library. example from my code
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("My Sheet 1");
ws.Cell("A8").Value = "Print by Admin:";
ws.Cell("B8").Value = $"{GetUserById(userId).name} - {GetUserById(userId).position_name}";
ws.Range("B8:C8").Merge();
var range = ws.Cell("B12").InsertTable(data);
range.Style.Border.TopBorder = XLBorderStyleValues.Thin;
range.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
range.Style.Border.RightBorder = XLBorderStyleValues.Thin;
range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
ws.Row(12).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(12).Style.Font.Bold = true;
MemoryStream stream = (MemoryStream)GetStream(wb);
return File(stream.ToArray(), ""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"", "yourfilename.xlsx");
here code for Getstream:
public Stream GetStream(XLWorkbook excelWorkbook)
{
Stream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}

How do I format my export to excel workbook in microsoft.office.interop.excel?

I have this export function that allows me to export 2 grid views into 2 separated worksheets in one excel.
But my problems are:
How can I have a usual popup window like usual download when I click on export button to prompt user to OPEN, SAVE AS, CANCEL of the download instead of saving it to a specific location (currently what I am doing in my codes)?
How can I set a code to enable wraptext = true for all my cells and also auto format the column height and width to fixed all the text so that it does not show ###### for date as an example when column width is too small when excel is opened.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
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);
String DT1 = "Data table 1";
String DT2 = "Data table 2";
ExportToExcel(app, workbook, Gridview1, DT1, 1);
ExportToExcel(app, workbook, Gridview2, DT2, 2);
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// 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
worksheet = (Excel.Worksheet)workbook,Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
//save the application
workbook.SaveAs(#"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
Modify the path of the excel file to save to a virtual path as follows
workbook.SaveAs(#"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
change this to
workbook.SaveAs(#"~/ExcelFiles/Filename.xlsx" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Try the following code for displaying save as dialog
String FileName = "FileName.xlsx";
String FilePath = "~/ExcelFiles/FileName.xlsx";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
Try this:
Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
as specified by Laxmikant modify the code of your method "ExportToExcel" as follows.
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// see the excel sheet behind the program
app.Visible = true;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
I removed these two lines of code and now there is no need of the parameter "Sheetid"
Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
worksheet = workbook.ActiveSheet;
Hope this will solve your issue
you haven't added worksheet in Workbook
try below code
worksheet = (Excel._Worksheet)oXL.Worksheets.Add();
worksheet.Name = SheetName;
set your headers using rangs
string[] colNames = new string[gv.Columns.Count];
int col = 0;
foreach(gvvolumns dc in GridView.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;

How do I export 2 gridviews into 2 separate sheets in one MS Excel file?

How do I export 2 gridviews (GridView1 & GridView2) into 2 separate sheets in one MS Excel file with the click of 1 button? Currently, I'm able to export only 1 gridview to an Excel sheet which the filename is the same as the sheet name. But I would like to 2 gridviews into 2 separate sheets which I would like sheet name to be define/set by myself. Thanks
public void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName ="Export"+DateTime.Now+".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
you need to modifiy your code so that you will create a worksheet in the excel file and manually copy the data from grid to excel file and create this code as a function that takes grid,sheetname and sheetid like 1 ,2 and so on as arguments and then within button click event call it twice once for grid1 and once for grid2 with different sheetnames and sheet ids 1 and 2 respectively. the code for the function is as follows.
Write these two line of code in button click event and after that call the function twice once for each grid by passing excel app and workbook also as arguments.
// creating Excel Application
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);
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook,GridView gridview,string SheetName,int sheetid)
{
// 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
worksheet = workbook.Sheets["Sheet"+ sheetid];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = sheetname;
// storing header part in Excel
for(int i=1;i<gridview.Columns.Count+1;i++)
{
worksheet.Cells[1, i] = gridview.Columns[i-1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i=0; i < gridview.Rows.Count-1 ; i++)
{
for(int j=0;j<gridview.Columns.Count;j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
//Edit my answer since there is only 1 export button:
Take a look at this question:
firstly add these namespace:
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
So basically you should have (or go ahead and make them) 2 DataTable (to bind to 2 gridviews): dt1 and dt2
Make a dataset and add 2 datatables to it
DataSet dataset = new DataSet();
dataset.Tables.Add(dt1);
dataset.Tables.Add(dt2);
then
//Print using Ofice InterOp
Excel.Application excel = new Excel.Application();
var workbook = (Excel._Workbook)(excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
//NOTE: Excel numbering goes from 1 to n
var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
string outfile = #"C:\APP_OUTPUT\EXCEL_TEST.xlsx";
workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();
to change worksheet name, I believe you can do:
currentSheet.Name = "your sheet name"

How to copy excel worksheets Into another excel workbook without opening the excel file in c# winforms?

In C# windows application,
I have many excel workbooks, what i want is to copy the worksheets from the excel workbook to a single workbook.
This is possible, but i have to open the excel workbooks in order to do so.
Excel.Application app = new Excel.Application();
app.Visible = true;
app.WindowState = XlWindowState.xlMinimized;
app.Workbooks.Add("");
app.Workbooks.Add(#"Path\WorkBook1.xlsx");
app.Workbooks.Add(#"Path\WorkBook2.xlsx");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
int count = app.Workbooks[i].Worksheets.Count;
app.Workbooks[i].Activate();
for (int j = 1; j <= count; j++)
{
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Select(true);
ws.Cells.Select();
Excel.Range sel = (Excel.Range)app.Selection;
sel.Copy(Type.Missing);
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
sheet.Paste(Type.Missing, Type.Missing);
sheet.Name = app.Workbooks[i].Worksheets[j].Name;
}
}
app.DisplayAlerts = false;
app.Workbooks[3].Close();
app.Workbooks[2].Close();
app.DisplayAlerts = true;
Cursor = Cursors.Default;
MessageBox.Show("Successfully Generated Excel...!", "Excel Tool", MessageBoxButtons.OK, MessageBoxIcon.Information);
Is is possible without opening the excel sheets, copy all the data with their styles ?
To copy a worksheet and all its contents and formatting without selecting and copying the contents of the worksheet itself you can make use of Worksheet.Copy. You'd use it like so:
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
ws.Copy(Before: sheet);
If, however, what you actually mean by your question is that you want to copy the contents of the workbooks into one common workbook without ever opening the file, then I don't believe that's possible. You need to open the file to access the data.

Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)) [duplicate]

This question already has an answer here:
Microsoft.Office.Interop.Excel doesn't work on 64 bit
(1 answer)
Closed 8 years ago.
The error appeared when exporting data in a datagrid view to an Excel sheet:
error (Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)))
on this line:
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
How do I fix this problem?
My full code:
private void button1_Click(object sender, EventArgs e)
{
System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
// Creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
// Creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// Creating new Excel sheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// See the Excel sheet behind the program
//Funny
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 Ketoan";
// Storing header part in Excel
for (int i = 1; i < DGData.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGData.Columns[i - 1].HeaderText;
}
// Storing each row and column value to Excel sheet
for (int i = 0; i < DGData.Rows.Count - 1; i++)
{
for (int j = 0; j < DGData.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = DGData.Rows[i].Cells[j].Value.ToString();
}
}
// Save the application
string fileName = String.Empty;
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 (System.Exception ex)
{
}
finally
{
app.Quit();
workbook = null;
app = null;
}
}
Consider:
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
Delete this line or move to under the line that closes the Excel application.
It works for me.
The real reason is the regional settings configured for the user that launches the thread. It is documented as a bug.
http://support.microsoft.com/default.aspx?scid=kb;en-us;320369
Your code works fine on Office 2007 + VS 2010. What versions are you using? Mayby you have choosen wrong version of interop refernece: Office 2007 = 12.0.0.0, Office 2010 = 14.0.0.0
You can look at http://support.microsoft.com/default.aspx?scid=kb;en-us;320369 it might solve your problem.
I had the same problem and I solved it:
Look at this:
Microsoft.Office.Interop.Excel doesn't work on 64 bit
You should type this line:
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
Do this after you close your Excel application; before adding WorkBook you should not use this line.

Categories