2016-08-26 62 views
0

我需要知道如何將DataGridView中的行導出到Excel,包括它們的行顏色。如何將DataGridView行與其行顏色導出到MS Excel工作表?

此時我輸出它們,但顏色爲空白/默認顏色。

我需要這樣做在vb.net

+1

如何導出它們?如果可以,請發佈您的代碼,以便我們可以提出最簡單的更改。沒有更多細節,這個問題有太多可能的答案。 – Slai

+0

您是否使用excel-interop,xml格式或任何其他可能的解決方案導出爲ex​​cel? –

回答

1

你可以試試這個:

For Each drow As DataGridViewRow In datagrid1.Rows 
     xcel.Cells(yourRowInt, yourColInt).Interior.Color = drow.DefaultCellStyle.BackColor 
    Next 
+0

如果有效,請接受此答案。我有一個_reputation_來建立。大聲笑。 :D –

+0

我不認爲StackOverflow上的聲望是任何真正的[使用](http://programmers.stackexchange.com/questions/20407/will-high-reputation-in-stack-overflow-help-to-得到一份好工作),除非你試圖像打一場比賽,並獲得高分和升級xD。這看起來像它只會格式化第一個單元格,所以可能類似'xcel.Cells(drow.Index + 1,yourColInt).Resize(0,drow.Cells.Count).Interior.Color' – Slai

+0

行和列索引你決定。我只是給你提供了基於網格改變單元格顏色的想法。回覆,我和我的朋友都是程序員,我們用它來互相吹噓。 :d –

0

你可以嘗試這樣的嗎?

Private Sub button5_Click(ByVal sender As Object, ByVal e As EventArgs) 
     Const WORKSHEETSTARTROW As Integer = 1 
     Const WORKSHEETSTARTCOL As Integer = 1 
     Dim excelApp = New Excel.Application 
     excelApp.Visible = true 
     Dim excelbk As Excel.Workbook = excelApp.Workbooks.Add(Type.Missing) 
     Dim xlWorkSheet1 As Excel.Worksheet = CType(excelbk.Worksheets("Sheet1"),Excel.Worksheet) 
     Dim worksheetRow As Integer = WORKSHEETSTARTROW 
     Dim rowCount As Integer = 0 
     Do While (rowCount _ 
        < (dataGridView1.Rows.Count - 1)) 
      Dim worksheetcol As Integer = WORKSHEETSTARTCOL 
      Dim colCount As Integer = 0 
      Do While (colCount _ 
         < (dataGridView1.Columns.Count - 1)) 
       Dim xlRange As Excel.Range = CType(xlWorkSheet1.Cells(WORKSHEETSTARTROW, worksheetcol),Excel.Range) 
       xlRange.Value2 = dataGridView1.Columns(colCount).Name 
       worksheetcol = (worksheetcol + 1) 
       If (Not (dataGridView1.Rows(rowCount).Cells(colCount).Style.Font) Is Nothing) Then 
        xlRange.Font.Bold = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Bold 
        xlRange.Font.Italic = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Italic 
        xlRange.Font.Underline = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.Underline 
        xlRange.Font.FontStyle = dataGridView1.Rows(rowCount).Cells(colCount).Style.Font.FontFamily 
       End If 

       worksheetcol = (worksheetcol + 1) 
       colCount = (colCount + 1) 
      Loop 

      worksheetRow = (worksheetRow + 1) 
      rowCount = (rowCount + 1) 
     Loop 

    End Sub 
相關問題