2011-03-03 28 views
12

apareció el error al exportar datos en una vista de cuadrícula de datos a una hoja de Excel:.Antiguo formato o biblioteca de tipo no válido. (Excepción de HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))

error (Formato antiguo o biblioteca de tipos no válida (Excepción de HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)))

en esta línea:

Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); 

¿Cómo puedo solucionar este problema?

Mi código completo:

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; 
    } 
} 
+0

Podría formatear esto para que sea legible. –

+0

Usted ya hizo esta pregunta aquí: http://stackoverflow.com/questions/5179196/error-when-export-datagrid-view-to-excel-sheet/5179312#5179312 –

+1

Es debido al lenguaje regional del sistema operativo que no sea " en-US ". Ya respondí esto en hyperneed.com. Para ver la respuesta, visite el siguiente enlace: http://www.hyperneed.com/ShowSearchAnswers.aspx?searchstring=&category=Programming&questionid=5afa16f5-653a-4f2e-afcb-c83dce5bc4e4 – michael

Respuesta

5

La verdadera razón es la configuración regional configurada para el usuario que lanza el hilo. Está documentado como un error.

http://support.microsoft.com/default.aspx?scid=kb;en-us;320369

+0

Esta es la verdadera razón y la solución es simplemente establecer la cultura a la cultura Excel antes de abrir y volver a la cultura anterior después del cierre. – kuklei

6

Considere:

System.Threading.Thread.CurrentThread.CurrentCulture = oldCI; 

Eliminar esta línea o mover a por debajo del umbral que cierra la aplicación de Excel.

Funciona para mí.

0

Debe escribir esta línea:

System.Threading.Thread.CurrentThread.CurrentCulture = oldCI; 

hacer esto después de cerrar la aplicación Excel; antes de agregar WorkBook, no deberías usar esta línea.

Cuestiones relacionadas