locked
Export GridView to Excel (xlsx, Excel 2007 Format) RRS feed

  • Question

  • User1485238302 posted

    Hi again,

    I was looking online for a way to export gridview to excel in Excel 2007 Format (xlsx). I could only find one solution, gridviewtoexcel. Is this the only way to do it?

    Thanks
    Bullpit

    Monday, February 18, 2008 11:53 AM

Answers

  • User1485238302 posted

    I did[:^)].This is my code: 

    protected void bttnExportXL_Click(object sender, EventArgs e)
        {
           gridViewMaster.AllowPaging = false;
           gridViewMaster.AllowSorting = false;
            Response.Clear();
    
            //Response.AddHeader("content-disposition", "attachment;filename=Report_"+ DateTime.Now.ToShortDateString() +".xlsx");
            Response.AddHeader("content-disposition", "attachment;filename=Report.xlsx");
            Response.Charset = "";
    
            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    
            //Response.ContentType = "application/vnd.xls";
            
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    
            foreach (GridViewRow r in gridViewMaster.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
                    {
                        r.Cells[columnIndex].Attributes.Add("class", "text");                    
                    }
                }            
            }
            
            gridViewMaster.RenderControl(htmlWrite);
            
            string style = @"&lt;style> .text { mso-number-format:\@; } </style> ";
            Response.Write(style);
          
            Response.Write(stringWrite.ToString());
            Response.End();
            
        }
    
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 18, 2008 1:46 PM
  • User-2106054853 posted

    Hi:

      Excel 2007 cannot recognize the pure html format. You'd better use xls as the extension or render the excel format to client end.

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 20, 2008 12:58 AM

All replies

  • User-483064448 posted


    Hey Bullpit,


    Please, do the following :



    1st in the html side of your page write this ...

    <%
    @ Page Language="VB" EnableEventValidation ="false"  AutoEventWireup="false" CodeFile="marquee.aspx.vb" Inherits="marquee" %>




    2nd this is the vb code

    protected void btnSubmit_Click(object sender, ImageClickEventArgs e)

    GridView1.DataSource = 'Place your datasource (datatable/dataset)

    GridView1.DataBind()

    Response.Clear()

    Response.Buffer = True

    Response.AddHeader("Content-Disposition", "attachment; filename=MyExcelFileName.xls")

    'Choose one of these: as the contentType

    'Excel 2003 : "application/vnd.ms-excel"

    'Excel 2007 : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

     

    Response.ContentType = "application/vnd.ms-excel"

    Dim writer As New System.IO.StringWriter()

    Dim html As New System.Web.UI.HtmlTextWriter(writer)

    GridView1.RenderControl(html)

    Response.Write(writer)

    Response.End()

    End Sub

    Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control) End Sub  


    and these links show step by step how to do that:

    1 -
    http://aspalliance.com/771
    2 - http://gridviewguy.com/ArticleDetails.aspx?articleID=86
    3 - http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx?ArticleID=000c64fb-8a22-414a-8247-984335aaa0eb


    Please, let me know if that helped ...

    Monday, February 18, 2008 11:57 AM
  • User1485238302 posted

    Thanks for your response but I am talking about xlsx format and not xls format.

    Monday, February 18, 2008 12:03 PM
  • User-483064448 posted



    Hey Bullpit,

    Welcome @ anytime ...


    Yup this one export 2007 format ...

    just replace the content type with this one

    'Excel 2007 : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

    Please, re-check the last post ..


    Best regards ...


    Monday, February 18, 2008 12:07 PM
  • User1485238302 posted

    I had already tried that before starting this thread. It didn't work, Excel cannot open the file exported this way saying that its either corrupted or the extension is not correct. Also, If I leave the extension as .xls, excel can open the file but then its not xlsx format, and if I changed the extension to .xlsx, I get the error.

    Monday, February 18, 2008 12:16 PM
  • User-483064448 posted

     

    Hey bullpit,

    Extension       MIME Type
    .xlsx               application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    .xltx                application/vnd.openxmlformats-officedocument.spreadsheetml.template
    .potx               application/vnd.openxmlformats-officedocument.presentationml.template
    .ppsx              application/vnd.openxmlformats-officedocument.presentationml.slideshow
    .pptx               application/vnd.openxmlformats-officedocument.presentationml.presentation
    .sldx               application/vnd.openxmlformats-officedocument.presentationml.slide
    .docx              application/vnd.openxmlformats-officedocument.wordprocessingml.document
    .dotx               application/vnd.openxmlformats-officedocument.wordprocessingml.template
    .xlam              application/vnd.ms-excel.addin.macroEnabled.12
    .xlsb               application/vnd.ms-excel.sheet.binary.macroEnabled.12

    These MIME types were added to IIS7 as noted in KB936496.

    BTW, the previous code worked fine with me !!!!!!

    Monday, February 18, 2008 12:35 PM
  • User1485238302 posted

    Response.AddHeader("Content-Disposition", "attachment; filename=MyExcelFileName.xls")

    Did you try MyExcelFileName.xlsx. ?

    This is the error I am getting when trying to open the exported file in excel:

    Excel cannot open the file "Report.xlsx" because the file format or extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

    Monday, February 18, 2008 1:30 PM
  • User-483064448 posted


    Edited:


    Sorry I'm not sure if I did ...

    [ I got this MIME while converting a ms-excel 2007 file to binary, and used it to write it back to ms-excel 2007 format and it worked fine !!! ]


    Did you change the content type, instead of :

    Response.ContentType = "application/vnd.ms-excel"

    put

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"   

    Please, let me know if that helped

    Monday, February 18, 2008 1:42 PM
  • User1485238302 posted

    I did[:^)].This is my code: 

    protected void bttnExportXL_Click(object sender, EventArgs e)
        {
           gridViewMaster.AllowPaging = false;
           gridViewMaster.AllowSorting = false;
            Response.Clear();
    
            //Response.AddHeader("content-disposition", "attachment;filename=Report_"+ DateTime.Now.ToShortDateString() +".xlsx");
            Response.AddHeader("content-disposition", "attachment;filename=Report.xlsx");
            Response.Charset = "";
    
            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    
            //Response.ContentType = "application/vnd.xls";
            
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    
            foreach (GridViewRow r in gridViewMaster.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
                    {
                        r.Cells[columnIndex].Attributes.Add("class", "text");                    
                    }
                }            
            }
            
            gridViewMaster.RenderControl(htmlWrite);
            
            string style = @"&lt;style> .text { mso-number-format:\@; } </style> ";
            Response.Write(style);
          
            Response.Write(stringWrite.ToString());
            Response.End();
            
        }
    
     
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 18, 2008 1:46 PM
  • User-2106054853 posted

    Hi:

      Excel 2007 cannot recognize the pure html format. You'd better use xls as the extension or render the excel format to client end.

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 20, 2008 12:58 AM
  • User1485238302 posted

    Excel 2007 cannot recognize the pure html format. You'd better use xls as the extension or render the excel format to client end.

    Oh...so you mean I can't do it? Or is there a workaround?

    Thanks,
    Bullpit

    Wednesday, February 20, 2008 8:04 AM
  • User-2106054853 posted

    Hi:

      A workaround is to create xslx file at server end. Write that file and redirect user to it to force the download dialog popup. Though it's very slow since you've to access hard disk instead of memory.

      To do this you can use excel interop:

    http://msdn.microsoft.com/en-us/library/wss56bz7(vs.80).aspx

    http://msdn.microsoft.com/en-us/library/syyd7czh(VS.80).aspx

      Comparing with this I think you'd opt to use xsl as the extension.

      BTW, to correct my statement in my previous post. What I mean is a file with xslx extension but pure html format cannot be recognized by excel 2007.

    Regards

    Wednesday, February 20, 2008 8:46 PM
  • User-1302569877 posted

    Hello Chen,

       So you mean to say if I use .xsl as the extension I should be able to view the file even if I have office 2007 installed on the client computer?

    here is the code that I use for creating the excel file which works fine of Excel 2000 but not on 2007

    Response.Clear();

    Response.Buffer =
    true;

    Response.ContentType = "application/vnd.ms-excel";

    Response.ContentEncoding = System.Text.Encoding.UTF7;

    Response.AddHeader("content-disposition", "attachment; filename=" + "MyFile.xsl");

    When I use this code I get the same error message as bullpit gets.

    How did the code work for XGmarX when it did not work for me and bullpit?

    Bullpit did you find a solution for this problem other than creating a file on the server and redirecting the user to it?

    Thanks

    Wednesday, February 27, 2008 2:14 PM
  • User1485238302 posted

    Bullpit did you find a solution for this problem other than creating a file on the server and redirecting the user to it?

    Nope, I didn't. Since it was not an immediate requirement for me, I let it go for now. Let's see if we get a solution from someone.

     

    Wednesday, February 27, 2008 3:04 PM
  • User-1302569877 posted

    Hey Bullpit,

    I think I got 95% of the solution. The 5% I did not get is when Excel opens and pops out the same message saying "The file you are trying to open bla bla bla" and I don't know for now how to get rid of it but on that message when I click yes I see my report or excel file. So try using this code for the header.

     Response.Clear();

    Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");

    Response.Charset = "";

    Response.ContentType = "application/vnd.xls"; // This was where the mistake was in my old code Response.ContentType = "application/vnd.ms-excel";

    Hope this works for you too.

    MJ

    Wednesday, February 27, 2008 3:44 PM
  • User1485238302 posted

    MJ-

    You are going back to square 1. Export to xls format was never a problem. We are looking for exporting to xlsx format.

    Wednesday, February 27, 2008 4:08 PM
  • User-1671087770 posted

     I'm trying to export a gridview to excel, I'd rather xls because not everyone has the new verison of office nor the nouse to go and get the document converter from microsoft.

    I've used the code for exporting xls, and excel 07 gives that annoying message everytime. This is really bad news, makes the process really un-friendly for users, especially those that get scraed by error messages. Asking users to follow instructions for saying yes, you can open the file to excel, then telling them how to save it as a propper xls (rather than html code, which is what is produced) is really tricky.

    Crap this.......... 

    Thursday, February 28, 2008 11:00 AM
  • User1485238302 posted

    It sure is...

    Thursday, February 28, 2008 11:39 AM
  • User426046264 posted

    Hi

    I too face the same problem and resolved too..

    Solution: First write Response.Write code and then set other response properties like AddHeader, ContentType etc

     

    Thursday, March 27, 2008 10:50 AM
  • User1485238302 posted

    Can you post your code?

    Thursday, March 27, 2008 10:51 AM
  • User-309740890 posted

    This error occures when trying to open xls file with excel 2007.

    Try this:

    1. Open your Registry (Start -> Run -> regedit.exe)
    2. Navigate to HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY
    3. Right click in the right window and choose New -> DWORD
    4. Type “ExtensionHardening” as the name (without the quotes)
    5. Verify that the data has the value “0″
    Friday, April 4, 2008 3:44 PM
  • User730785594 posted

     

    I started with this problem yesterday afternoon and Google led me to this thread.

    Has anyone reached a solution?  I looked it my registry, that string wasn't found.

    Friday, May 2, 2008 8:31 AM
  • User-1763611275 posted

    try this

     

     

    protected void Button1_Click(object sender, EventArgs e)
    {
    Response.Clear();
    
    Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
    
    Response.Charset = "";
    
    // If you want the option to open the Excel file without saving than
    
    // comment out the line below
    
    // Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
    Response.ContentType = "application/vnd.xls";
    
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    
    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);
    
    GridView1.RenderControl(htmlWrite);
    
    Response.Write(stringWrite.ToString());
    
    Response.End();
    
    }
    
    public override void VerifyRenderingInServerForm(Control control)
    {
    
    // Confirms that an HtmlForm control is rendered for the
    //specified ASP.NET server control at run time.
    
    }
    
     
    Saturday, May 3, 2008 10:12 PM
  • User1485238302 posted

    try this

    And what would this do?

     

    Monday, May 5, 2008 7:45 AM
  • User730785594 posted

    I used different code entirely because I realized I needed to open Excel with more than one tab.  Once I did that, the warning prompt was no longer displayed.  Here's my code if you'd like to give it a try:

     

    Sub GenerateThreeTabs(ByVal inParam As Integer)

    Dim ds As New DataSet

    Dim connString As String = _

    ConfigurationManager.ConnectionStrings("ConnectToMyDb").ConnectionString

    Dim conn As New SqlConnection(connString)Dim command As New SqlCommand()

    command.CommandType = CommandType.StoredProcedure

    command.Connection = conn

    command.CommandText = "up_MyStoredProcedure"

    command.Parameters.Add(New SqlParameter("@param", Data.SqlDbType.Int))

    command.Parameters("@param").Value = inParam

    Dim adapter As New SqlDataAdapter(command)

    Try

    adapter.Fill(ds)

    Catch ex As ExceptionResponse.Write("Submit() Exception " + ex.Message)

    conn.Close()

    conn.Dispose()

    conn = Nothing

    Exit Sub

    End Try

    ' Create Excel Application, Workbook, and WorkSheets

    Dim xlExcel As New Excel.Application

    Dim xlBooks As Excel.Workbooks

    Dim xlBook As Excel.Workbook

    Dim xlSheets As Excel.Sheets

    Dim stdSheet As Excel.Worksheet Dim xlCells As Excel.Range

    Dim sFile As String

    Dim rescSheet As Excel.Worksheet Dim rescSheet2 As Excel.Worksheet

    sFile = Server.MapPath(Request.ApplicationPath) & "\Excel.xls"

    xlExcel.Visible = False : xlExcel.DisplayAlerts = False

    ' Get all workbooks and open first workbook

    xlBooks = xlExcel.Workbooks

    xlBooks.Open(Server.MapPath(Request.ApplicationPath) &
    "\Commissions.xls")

    xlBook = xlBooks.Item(1)

    ' Get all sheets available in first book

    xlSheets = xlBook.Worksheets

    ' Process the summary sheet with results from stored proc's first query - tables(0).

    stdSheet = CType(xlSheets.Item(1), Excel.Worksheet)

    xlCells = stdSheet.Cells

    GenerateSummaryTab(ds.Tables(0), xlCells)

    ' Get the month details sheet with results from stored proc's second query - tables(1).

    rescSheet = CType(xlSheets.Item(2), Excel.Worksheet)

    xlCells = rescSheet.Cells

    GenerateMonthDetails(ds.Tables(1), xlCells)

    ' Get the history sheet with results from stored proc's third query - tables(2).

    ' Also pass in the agent's name from tables(0).

    rescSheet2 = CType(xlSheets.Item(3), Excel.Worksheet)

    xlCells = rescSheet2.Cells

    GenerateMeterSignupHistoryTab(ds.Tables(0).Rows(0).Item(
    "Agent").ToString, ds.Tables(2), xlCells) xlExcel.Visible = True

     

    End Sub

    Private Sub GenerateMonthDetails(ByRef table As DataTable, ByVal xlCells As Excel.Range)

    Dim dr As DataRow, ary() As Object

    Dim iRow As Integer, iCol As Integer

    'Output Column Headers

    For iCol = 0 To table.Columns.Count - 1

    xlCells(1, iCol + 1) = table.Columns(iCol).ToString

    Next

    'Output Data

    Try

    For iRow = 0 To table.Rows.Count - 1

    dr = table.Rows.Item(iRow)

    ary = dr.ItemArray

    For iCol = 0 To UBound(ary)

    xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString

    Next

    Next

    Catch ex As Exception

    Response.Write(ex.Message)

    End Try

    End Sub

    Private Sub GenerateSummaryTab(ByRef table As DataTable, ByVal xlCells As Excel.Range)

    xlCells(1, 2) = table.Rows(0).Item("Agent").ToString

    xlCells(5, 2) = table.Rows(0).Item("Commission").ToString

    xlCells(5, 3) = table.Rows(0).Item("Usage").ToString

    xlCells(5, 4) = table.Rows(0).Item("Storage").ToString xlCells(5, 5) = table.Rows(0).Item("Margin").ToString

    End Sub

    Private Sub GenerateMeterSignupHistoryTab(ByVal sAgentName As String, ByRef table As DataTable, ByVal xlCells As Excel.Range)

    Dim iRow As Integer

    xlCells(1, 1) = sAgentName

    For iRow = 0 To table.Rows.Count - 1

    xlCells(iRow + 2, 2) = table.Rows(iRow).Item("mnth").ToString

    xlCells(iRow + 2, 3) = table.Rows(iRow).Item("cnt").ToString

    Next

    End Sub

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)

    End Sub

     

    HTH and good luck.  What a pain this problem was!

    Monday, May 5, 2008 8:05 AM
  • User1485238302 posted

    Thanks for the code. I would assume that this method requires Excel to be installed on server!?

    Monday, May 5, 2008 8:08 AM
  • User730785594 posted

    I'm not 100% sure.  We have Excel on the server and my customers have it too, and I know who my customers are and have control over their software (nice to have things easy,huh?)

     But here's the original link where I got my code, if you want to see its origin.

    http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=283

    Monday, May 5, 2008 8:27 AM
  • User-1465957831 posted

    I am surprised to see that there is no clear solution for this problem so far.

    I am facing the same problem. I want to export DataTable to excel 2007 because there is some limitations with Excel 2003 where you can only work on 65,000 records and I am supposed to deal with more than 10,00,000 records at a time which is only possible through Excel 2007.

     
    It would be a great help to me if any one can come up with solution.

    Thanks !
     

    Friday, August 8, 2008 1:26 AM
  • User-1671087770 posted

     surely the asp.net team woul'd have known we'll want to export things to excel 2007?

    None of the mods or bods at microsoft got an answer to this? 

    Tuesday, August 12, 2008 4:11 AM
  • User1820632489 posted

    hii

    i hv done all code for Export GridView to Excel and its working fine.

    but when i m going to open excel file , for some content like this

    1)ACCF Procedure – 1 of 4  it display like this  ACCF Procedure – 1 of 4

    2)References – 1 of 7 it display like this  References – 1 of 7.

    from above i think big dash sign creating problem.but i m not sure. why its display like this –.

    please help me for this problem.



     

     


    Thursday, October 23, 2008 9:40 AM
  • User852875298 posted

    Hi, I'm rendering data from a DataTable to a temp Excel file on client side, and it's working for Excel 2003 + browers IE7/Firefox 3. I'm supprised to see that the MIME type specified for Response.ContentType does NOT even matter. A blank string will work just fine! I guess the most current browsers know by file extensions to which application they should call when asking for opening a known file type? My code is as below and it works on ASP.NET 2.0 on both WinXP and Win2003 platforms (only tested with Excel 2003 though, have not installed Excel 2007, which is too big for a slow PC):

        protected void btnViewExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = GetTdDataDable(); //build a DataTable with a private method that is not shown here

            if (!Response.IsClientConnected)
            {//if client no longer connected for a length query, end the Response. Might not work for W2k3 & IIS6
                Response.End();
            }

            GetExcelFromDataTable(dt, Resources.Strings.FileResultXls); //defined an Excel temp file name in the Strings file stored in the App_GlobalResources folder
        }

        /// <summary>
        /// Create an Excel file from a DataTable object and send to browser for client to open/download.
        /// </summary>
        /// <param name="dt">The DataTable object that contains the data needs to be converted into an Excel file</param>
        /// <param name="fileName">A name for the Excel file</param>
        private void GetExcelFromDataTable(DataTable dt, string fileName)
        {
            string attachment = "attachment; filename=" + fileName;
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            //application names below for MIME types of different Excel versions don't seem
            //important to the most current browsers. Even an empty string will work.
            //Response.ContentType = "application/vnd.ms-excel"; //Excel 2003
            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //Excel 2007
            Response.ContentType = string.Empty;

            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();
        }
     

    Thanks. John

    P.S. Forgot to mention, this might be working for Excel 2007, too, since the MIME type string doesn't even matter. I don't have Excel 2007 installed but if anyone is interested to try, please post your result for your test. Thanks a lot.

    Thursday, November 13, 2008 9:14 PM
  • User1861167505 posted

     I change the content type as per forum but i still get same error.

    my code is like this:

    Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";       
    Response.Charset = "";  

     

    string strFile = "Search_Data_" + System.DateTime.Now.Day.ToString() + month + System.DateTime.Now.Year.ToString() + ".xls";

    I also tried file name without any extension

    string strFile = "Search_Data_" + System.DateTime.Now.Day.ToString() + month + System.DateTime.Now.Year.ToString() ;

     

    Error like this :

    The file you are trying to open , .xls' is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open the file now ?

     

    Is anyone have solution other than changes in registry file  for this issue ?

     

     

     

     

    Friday, December 19, 2008 1:41 AM
  • User1861167505 posted

     I change the content type as per forum but i still get same error.

    my code is like this:

    Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";       
    Response.Charset = "";  

     

    string strFile = "Search_Data_" + System.DateTime.Now.Day.ToString() + month + System.DateTime.Now.Year.ToString() + ".xls";

    I also tried file name without any extension

    string strFile = "Search_Data_" + System.DateTime.Now.Day.ToString() + month + System.DateTime.Now.Year.ToString() ;

     

    Error like this :

    The file you are trying to open , .xls' is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open the file now ?

     

    Is anyone have solution other than changes in registry file  for this issue ?

     

    Thanks,

    Umesh

    umesh.chape@aurovision.com

     

     

     

    Friday, December 19, 2008 1:43 AM
  • User1820632489 posted

    try this .

    if youu want to show your grid data in excel file then use below code.

    HttpContext.Current.Response.ClearContent();

    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + strHeading + ".xls");

    HttpContext.Current.Response.ContentType = "application/excel";

     

    Thanks & Regards

    Jony shah

    Saturday, December 20, 2008 5:20 AM
  • User1372017629 posted

    Hi

    I have my application running in Windows 2000 and uses Office 2000.

     Below is the code wrriten to export excel file 

    Response.ContentType = "application/vnd.ms-excel"

    If i try to run the same code in VISTA or XP which uses Office 2007.

    I am getting below error.

    "The format not supported ... " what it could be the cause and how to resolve this.

    Irrespective of Windows 2000 (Office 2000) , VISTA (Office 2007) or XP(Office 2007).

    Kindly help in this

    Thanks

    Mwalter.

     

     

     

    Monday, December 22, 2008 8:43 PM
  • User1861167505 posted

     That message is microsoft warning message.To remove that warning message please do following steps:

     

    1) Run -   regedit
    2) Navigate path - HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY
    3) Rightclick --> new>DWORD>
    4) add key ExtensionHardening
    5) value = 0

     It works for me in Office 2007.

    Please try this and let me know Is it helpful to you or not.

     

    Thanks,

    Umesh

     

     

     

     

     

    Monday, December 22, 2008 11:43 PM
  • User1372017629 posted

    Hey Umesh 

    Thanks, I really appreciate it.

    Is there any other way that we can fix this by common code change.

    Making registry entry in all client machine is not possible.

    Kindly advise.

    Walter. 

     

    Tuesday, December 23, 2008 12:00 AM
  • User1861167505 posted

     Hi Walter,

                   Please try this.

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    I found this on fourm but it is not working for me. try at your site becasue this is working for many people as per fourm.If you found any solution please let me know.

     

    Regards,

    Umesh

    Tuesday, December 23, 2008 12:38 AM
  • User1372017629 posted

    HI Umesh

    My client has Office 2000 in server m/c , and an application pushes all data into EXCEL file.

    now if i access (in XP/VISTA which has Office 2007 installed) that aplication to view the EXCEL file  

    am facing the problem.

    my concern is i need fix this in my client m/c.

    Kindly advise.

    Mwalter.

     

     

    Wednesday, December 24, 2008 11:57 PM
  • User-1450944786 posted

    Hi

     This is vamshi from Hyd facing same problem 

     To save more than 1 lakh records in excel 2007 format , U have got any solutions please can u inform me

     

    thanks

    Monday, March 2, 2009 6:38 AM
  • User1861167505 posted

    Hi Vanshi,

    I think  below is the only solution to solve this , because that is warning message by Microsoft.

    Run -   regedit
    Navigate path - HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\12.0\EXCEL\SECURITY
    Rightclick --> new>DWORD>
    add key ExtensionHardening
    value = 0

     

    Thanks,

    Umesh


    Monday, March 2, 2009 6:50 AM
  • User1372017629 posted

    Hi

    I have faced below issues when i migrate my .NET application accessing Office 2003 to Office 2007. 

    Refer the link .. under each issue

    Issue 1:

    Error message:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>The file you are trying to open, 'name.ext', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?<o:p></o:p>Description:<o:p></o:p>The warning message is a user-notification function that was added to Excel 2007. The warning message can help prevent unexpected problems that might occur because of possible incompatibility between the actual content of the file and the file name extension.<o:p></o:p>

    Reason is MS Office 2007 uses XML formatter and MS Office 2000 uses HTML formatter. 

    Microsoft link to refer:  http://support.microsoft.com/kb/948615

    <o:p></o:p>Remedy:<o:p></o:p>

    To restrict this warning message we need to make a entry in registry in all the client machines.

    1.       Start Registry Editor.

    <o:p></o:p>2.       Locate and then click the following registry sub key: HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security<o:p></o:p>3.       On the Edit menu, point to New, and then click DWORD Value. <o:p></o:p>4.       Type ExtensionHardening, and then press ENTER. <o:p></o:p>5.       Right-click ExtensionHardening and then click Modify. <o:p></o:p>6.       In the Value data box, type the value data, and then click OK.<o:p></o:p>

     

    Issue 2:

    Interaction between Office Excel 2007 and Internet Explorer

    <o:p></o:p>When a user navigated to a Microsoft Office document from within Internet Explorer in earlier versions of the Microsoft Office suites, the document opened with the program that was hosted inside the Internet Explorer program. Many developers used this functionality to create a more integrated interaction between their Web programs and the data that was produced by those programs, such as creating a workbook and then instructing Internet Explorer to navigate to that workbook. However, this caused confusion for users who wanted to work with documents from the Web (Internet or intranet), because the full Office Excel user interface was not available from within Internet Explorer.<o:p></o:p>This default behavior is changed in the 2007 Office system. The program does not open inside Internet Explorer. Instead, the appropriate Microsoft Office program launches and opens the document. This provides a more consistent experience; however, it may cause unexpected behavior in custom applications that use Internet Explorer. Although this is the default behavior, users can choose to revert to the earlier hosted behavior if that is what they prefer.<o:p></o:p>

    Microsoft link to refer: http://technet.microsoft.com/en-us/library/cc179188.aspx

    Remedy:

    <o:p></o:p>·         In Windows Explorer, you click Tools, and then you click Folder Options. <o:p></o:p>·         On the File Types tab, you select a 2007 Microsoft Office file type, such as DOCX, PPTX, or XLSX, in the list of file types. <o:p></o:p>·         You click Advanced and select Browse in same window.<o:p></o:p>

    Thanks

    Mwalter.

     

    Tuesday, March 3, 2009 10:37 PM
  • User1465001813 posted

    I found this: http://www.gemboxsoftware.com/WebDemo/Index.aspx, so easy and so GREAT!! I recommend this for those who have have problems exporting to Excel 2007(xlsx). The link also shows how to export to: CSV, XLS, XLSX, ODS, HTML






    Thursday, October 1, 2009 4:16 AM
  • User-1786377522 posted

    xlsx excel format is completely different form any other excel format. It's basically a zipped file! To verify this you can rename an xlsx file to zip and then double click it. You'll find a lot of xml files inside organized accordingly to Microsoft Office Open xml format.


    I Smile developed a tool (a dll) which allows an asp.net developer to export data to xls and xlsx starting from sqldatasource, sqldatareader, ecc with or without the use of a gridview.

    Of course it works without Office!

    You can find it at http://www.gridviewtoexcel.com.

    Hope this can help!

    Ettore

    Friday, December 18, 2009 3:56 AM