我编写了以下代码,用于将数据(包括图像)从datagridview导出到vb.net中的excel 一切都很好,除了图片没有放在他们想要的位置。我没有找到任何属于Shapes.addPicture()方法的方法来指定索引的位置。 在创建文件之后,默认情况下所有图片都是像堆栈一样在excel的开头。 这是代码。
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
Next
Dim count As Integer = 0
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.ColumnCount - 1
Dim cj = DataGridView1(j, i).Value
If (cj.GetType = GetType(System.Byte())) Then
Dim data As Byte() = DirectCast(cj, Byte())
Dim ms As New System.IO.MemoryStream(data)
Dim im As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
Dim h As String = "c:\h" + count.ToString + ".jpg"
im.Save(h, Imaging.ImageFormat.Jpeg)
xlWorkSheet.Shapes.AddPicture(h, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, i + 2, j + 1, 100, 100)
count += 1
Else
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
End If
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
Dim res As MsgBoxResult
res = MsgBox("Process completed, Would you like to open file?", MsgBoxStyle.YesNo)
If (res = MsgBoxResult.Yes) Then
Process.Start("d:\vbexcel.xlsx")
End If
答案 0 :(得分:1)
left
方法的top
和AddPicture
参数指定了从左上角开始的 points 中图片的左侧和顶部位置片。您似乎认为这将在单元格中。您需要以磅为单位计算单元格的大小并使用这些数字。 excel中的图片位于网格“上方” - 而不是“在”网格中。