从vb .net导出datagridview后无法打开Excel电子表格

时间:2014-06-27 13:25:25

标签: vb.net excel-interop

我有以下代码,它采用datagridview并将其内容导出到excel。这一切都很好。但是,我希望新的电子表格在完成后启动。目前,当它到达打开excel的行时,我收到以下错误:

  

Excel无法打开文件'exported.xlsx',因为文件格式或文件扩展名无效。验证文件是否已损坏,以及文件扩展名是否与文件格式匹配。

这是我的代码:

 Private Sub Button4_Click_1(sender As System.Object, e As System.EventArgs) Handles btlXLSExport.Click
    Dim fs As New IO.StreamWriter("C:\exported.xlsx", False)
    fs.WriteLine("<?xml version=""1.0""?>")
    fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
    fs.WriteLine("<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")
    fs.WriteLine("    <ss:Styles>")
    fs.WriteLine("        <ss:Style ss:ID=""1"">")
    fs.WriteLine("           <ss:Font ss:Bold=""1""/>")
    fs.WriteLine("        </ss:Style>")
    fs.WriteLine("    </ss:Styles>")
    fs.WriteLine("    <Worksheet ss:Name=""Sheet1"">")
    fs.WriteLine("        <ss:Table>")
    For x As Integer = 0 To dgCustomers.Columns.Count - 1
        fs.WriteLine("            <ss:Column ss:Width=""{0}""/>",
                     dgCustomers.Columns.Item(x).Width)
    Next
    fs.WriteLine("            <ss:Row ss:StyleID=""1"">")
    For i As Integer = 0 To dgCustomers.Columns.Count - 1
        fs.WriteLine("                <ss:Cell>")
        fs.WriteLine(String.Format(
                     "                   <ss:Data ss:Type=""String"">{0}</ss:Data>",
                                  dgCustomers.Columns.Item(i).HeaderText))
        fs.WriteLine("                </ss:Cell>")
    Next
    fs.WriteLine("            </ss:Row>")
    For intRow As Integer = 0 To dgCustomers.RowCount - 2
        fs.WriteLine(String.Format("            <ss:Row ss:Height =""{0}"">",
                                  dgCustomers.Rows(intRow).Height))
        For intCol As Integer = 0 To dgCustomers.Columns.Count - 1
            fs.WriteLine("                <ss:Cell>")
            fs.WriteLine(String.Format(
                         "                   <ss:Data ss:Type=""String"">{0}</ss:Data>",
                                       dgCustomers.Item(intCol, intRow).Value.ToString))
            fs.WriteLine("                </ss:Cell>")
        Next
        fs.WriteLine("            </ss:Row>")
    Next
    fs.WriteLine("        </ss:Table>")
    fs.WriteLine("    </ss:Worksheet>")
    fs.WriteLine("</ss:Workbook>")
    fs.Close()

    Dim wapp As Microsoft.Office.Interop.Excel.Application

    Dim wsheet As Microsoft.Office.Interop.Excel.Worksheet

    Dim wbook As Microsoft.Office.Interop.Excel.Workbook

    ' Dim wrange As Microsoft.Office.Interop.Excel.Range

    ' Dim chartRange As Microsoft.Office.Interop.Excel.Range



    wapp = New Microsoft.Office.Interop.Excel.Application

    wbook = wapp.Workbooks.Open("C:\exported.xlsx")
    wsheet = wbook.Worksheets(1)


End Sub

感谢您的帮助!

0 个答案:

没有答案