Экспорт из DataGridView в MS Excel 2003 - Visual Basic .NET

Узнай цену своей работы

Формулировка задачи:

Вечер добрый. В общем нужно экспортировать таблицу DataGridView в MS Excel 2003. На форуме нашел всего одну тему посвященную соохранению в эксель, вот она Экспорт данных в Excel из DataGridView , судя по описанию она мне подходит, но не получается. Написано, что нужно подключить ссылку на Microsoft.Office.Interop.Excel. У меня studio 2010, ничего похожего не нашел. Прошу помочь с подключением этого кода или если у кого есть готовый рабочий код поделитесь пожалуйста
кстатит, вот тот код, выкладывал

DM_AND

Ссылку на Microsoft.Office.Interop.Excel
Листинг программы
  1. Private Sub Button2_Click(ByVal sender As System.Object, _
  2. ByVal e As System.EventArgs) Handles Button2.Click
  3.  
  4. Dim xlApp As Excel.Application
  5. Dim xlWorkBook As Excel.Workbook
  6. Dim xlWorkSheet As Excel.Worksheet
  7. Dim misValue As Object = System.Reflection.Missing.Value
  8. Dim i As Integer
  9. Dim j As Integer
  10. xlApp = New Excel.ApplicationClass
  11. xlWorkBook = xlApp.Workbooks.Add(misValue)
  12. xlWorkSheet = xlWorkBook.Sheets("sheet1")
  13. For i = 0 To DataGridView1.RowCount - 2
  14. For j = 0 To DataGridView1.ColumnCount - 1
  15. xlWorkSheet.Cells(i + 1, j + 1) = _
  16. DataGridView1(j, i).Value.ToString()
  17. Next
  18. Next
  19. xlWorkSheet.SaveAs("C:\DM.xls")
  20. xlWorkBook.Close()
  21. xlApp.Quit()
  22. releaseObject(xlApp)
  23. releaseObject(xlWorkBook)
  24. releaseObject(xlWorkSheet)
  25. MsgBox("Ваш файл сохранен в C:\DM.xls")
  26. End Sub

Решение задачи: «Экспорт из DataGridView в MS Excel 2003»

textual
Листинг программы
  1. Public Class Form1
  2.     Private Declare Function ShellEx Lib "shell32.dll" Alias "ShellExecuteA" ( _
  3.         ByVal hWnd As Integer, ByVal lpOperation As String, _
  4.         ByVal lpFile As String, ByVal lpParameters As String, _
  5.         ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer
  6.  
  7.     Private Sub exportExcel(ByVal grdView As DataGridView, ByVal fileName As String, _
  8.         ByVal fileExtension As String, ByVal filePath As String)
  9.  
  10.         ' Choose the path, name, and extension for the Excel file
  11.         Dim myFile As String = filePath & "\" & fileName & fileExtension
  12.  
  13.         ' Open the file and write the headers
  14.         Dim fs As New IO.StreamWriter(myFile, False)
  15.         fs.WriteLine("<?xml version=""1.0""?>")
  16.         fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
  17.         fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")
  18.  
  19.         ' Create the styles for the worksheet
  20.         fs.WriteLine("  <ss:Styles>")
  21.         ' Style for the column headers
  22.         fs.WriteLine("    <ss:Style ss:ID=""1"">")
  23.         fs.WriteLine("      <ss:Font ss:Bold=""1""/>")
  24.         fs.WriteLine("      <ss:Alignment ss:Horizontal=""Center"" ss:Vertical=""Center"" " & _
  25.             "ss:WrapText=""1""/>")
  26.         fs.WriteLine("      <ss:Interior ss:Color=""#C0C0C0"" ss:Pattern=""Solid""/>")
  27.         fs.WriteLine("    </ss:Style>")
  28.         ' Style for the column information
  29.         fs.WriteLine("    <ss:Style ss:ID=""2"">")
  30.         fs.WriteLine("      <ss:Alignment ss:Vertical=""Center"" ss:WrapText=""1""/>")
  31.         fs.WriteLine("    </ss:Style>")
  32.         fs.WriteLine("  </ss:Styles>")
  33.  
  34.         ' Write the worksheet contents
  35.         fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
  36.         fs.WriteLine("  <ss:Table>")
  37.         For i As Integer = 0 To grdView.Columns.Count - 1
  38.             fs.WriteLine(String.Format("    <ss:Column ss:Width=""{0}""/>", _
  39.             grdView.Columns.Item(i).Width))
  40.         Next
  41.         fs.WriteLine("    <ss:Row>")
  42.         For i As Integer = 0 To grdView.Columns.Count - 1
  43.             fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""1"">" & _
  44.                 "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
  45.                 grdView.Columns.Item(i).HeaderText))
  46.         Next
  47.         fs.WriteLine("    </ss:Row>")
  48.  
  49.         ' Check for an empty row at the end due to Adding allowed on the DataGridView
  50.         Dim subtractBy As Integer, cellText As String
  51.         If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else subtractBy = 1
  52.         ' Write contents for each cell
  53.         For i As Integer = 0 To grdView.RowCount - subtractBy
  54.             fs.WriteLine(String.Format("    <ss:Row ss:Height=""{0}"">", _
  55.                 grdView.Rows(i).Height))
  56.             For intCol As Integer = 0 To grdView.Columns.Count - 1
  57.                 cellText = grdView.Item(intCol, i).Value
  58.                 ' Check for null cell and change it to empty to avoid error
  59.                 If cellText = vbNullString Then cellText = ""
  60.                 fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""2"">" & _
  61.                     "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
  62.                     cellText.ToString))
  63.             Next
  64.             fs.WriteLine("    </ss:Row>")
  65.         Next
  66.  
  67.         ' Close up the document
  68.         fs.WriteLine("  </ss:Table>")
  69.         fs.WriteLine("</ss:Worksheet>")
  70.         fs.WriteLine("</ss:Workbook>")
  71.         fs.Close()
  72.  
  73.         ' Open the file in Microsoft Excel
  74.         ' 10 = SW_SHOWDEFAULT
  75.         ShellEx(Me.Handle, "Open", myFile, "", "", 10)
  76.     End Sub
  77.  
  78.     Private Sub Form1_Load(ByVal sender As System.Object, _
  79.         ByVal e As System.EventArgs) Handles MyBase.Load
  80.         ' Create a couple of rows
  81.         Dim row1() As String = New String() {"Joe", "Benjamin", vbNullString, "23"}
  82.         Dim row2() As String = New String() {"Michael", "", "Brown", "32"}
  83.         Dim row3() As String = New String() {"Phil", "Todd", "Lee", "42"}
  84.  
  85.         ' Add the rows to the DataGridView
  86.         DataGridView1.Rows.Add(row1)
  87.         DataGridView1.Rows.Add(row2)
  88.         DataGridView1.Rows.Add(row3)
  89.     End Sub
  90.  
  91.     Private Sub Button1_Click(ByVal sender As System.Object, _
  92.         ByVal e As System.EventArgs) Handles Button1.Click
  93.         ' Call the export sub
  94.         exportExcel(DataGridView1, "exportedData", ".xls", _
  95.             My.Computer.FileSystem.SpecialDirectories.Desktop)
  96.     End Sub
  97. End Class

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут