0

I have this export function that allows me to export 2 grid views into 2 separated worksheets in one excel.

But my problems are:

  1. 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)?

  2. 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);
            }
}
James Boer
  • 321
  • 4
  • 9
  • 28

4 Answers4

1

Try this:

Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
gemathus
  • 108
  • 9
  • Hi I have updated my codes according to your solution. Now I am able to populate the Gridview1 thanks . However Gridview2 worksheet created and populated thus I received the same error upon taking sheetid 2. Hope you can help me out on this thanks – James Boer Oct 14 '15 at 02:09
1

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

Ramesh Babu
  • 405
  • 4
  • 10
  • Hi Ramesh Babu, I have updated my questions. please take a look thanks . – James Boer Oct 15 '15 at 07:11
  • Verify the answer I posted to display save as dialog. – Ramesh Babu Oct 15 '15 at 11:04
  • sorry what are you trying mean? Pleasee refer to http://stackoverflow.com/questions/33146325/how-do-i-add-in-an-save-dialogue-function-in-my-export-to-excel-codes in my new post thanks – James Boer Oct 15 '15 at 11:08
  • I posted another answer in the same post to display save as dialog. Please have a look at it. – Ramesh Babu Oct 15 '15 at 11:35
  • Hi I have update my codes in --->> please refer to http://stackoverflow.com/questions/33146325/how-do-i-add-in-an-save-dialogue-function-in-my-export-to-excel-codes. Will reply on Monday thanks a lot. This post is abit messy already. sorry. – James Boer Oct 16 '15 at 10:25
1

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();
Ramesh Babu
  • 405
  • 4
  • 10
  • Hi I received this error Microsoft Excel cannot access the file 'C:\Users\testacc\Documents\~\ExcelFiles\DCA76310'. There are several possible reasons: • The file name or path does not exist. at 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); – James Boer Oct 16 '15 at 00:40
  • Hi Ramesh, I would like to thank you for your help all these while. In addition to this question that yet to be solve for the time being, I do have a additional important question for my export function in another post located here - http://stackoverflow.com/questions/33161193/how-do-i-export-ajaxcontroltookkit-tabpanel-contentswhich-consist-of-multiple-c I hope you can help me out on this thanks a lot:) – James Boer Oct 16 '15 at 01:52
  • Hi Sorry as I have no idea regarding exporting chart to excel – Ramesh Babu Oct 16 '15 at 09:44
  • How do I solve the error for the pop up dialogue? do you have any idea? – James Boer Oct 16 '15 at 09:55
  • anywhere in the code if you specify the path "c:\users\testacc\documents", remove it and everywhere use "~/" to get relative path of your website and it may solve the issue. – Ramesh Babu Oct 16 '15 at 09:59
  • I do have 2 workbook.save as because I would like to save directly into my server and another one to allow user to choose the path they would like to save. is it possible? – James Boer Oct 16 '15 at 10:04
  • but in my 1st saveas it does not consist of /documents/ so im not sure where they get this path from – James Boer Oct 16 '15 at 10:05
  • please post your code as it is so that I can verify and suggest any changes needed – Ramesh Babu Oct 16 '15 at 10:08
  • Hi I have update my codes in --->> please refer to http://stackoverflow.com/questions/33146325/how-do-i-add-in-an-save-dialogue-function-in-my-export-to-excel-codes. Will reply on Monday thanks a lot. This post is abit messy already. sorry. – James Boer Oct 16 '15 at 10:27
  • Please refer to my question description as well. thanks alot – James Boer Oct 16 '15 at 10:27
  • Hi, can you take a look at this? http://stackoverflow.com/questions/33213123/how-do-i-change-my-codes-from-office-interop-excel-to-openxml-sdk if you are able to help me out. thanks – James Boer Oct 20 '15 at 00:32
0

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;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Laxmikant
  • 588
  • 4
  • 11
  • Hi thanks for your reply. I tried adding worksheet = (Excel.Worksheet)workbook.Worksheets.Add(); replacing oXL with workbook as I believe it should be so. But I still receive the same error at the same line Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid]; where sheeted = 2 – James Boer Oct 14 '15 at 05:34
  • what is the purpose of Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid] .... worksheet is already added you can add your stuff directly to worksheet object which is already added in Workbook – Laxmikant Oct 14 '15 at 05:49
  • That is for me to take in the ID to take the gridview1 and gridview2. please advice thanks – James Boer Oct 14 '15 at 06:06
  • is that required to create xlsx or just for your understanding? If it is only for understanding then try something else – Laxmikant Oct 14 '15 at 06:08
  • The code is required. Anyway I received error at worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText; with the implementation of your codes. I have problem populating gridview2 header. But Im not sure why as since it works for gridview1 but why error in gridview2? I have updated my codes in this question as well – James Boer Oct 14 '15 at 06:17
  • In that case its not really dynamic as you set the specific range because both of my gridviews do not have the same number of columns – James Boer Oct 14 '15 at 08:23