我使用DataGridViews
将ClipboardCopyMode
导出到Excel。但是,我想格式化标题和单元格width/height
,因为单元格没有正常调整。
另外,我希望在DataGridView
的数据中添加一些数据。
这是我sub
的代码:
Dim appExcel As Excel.Application
Dim wbExcel As Excel.Workbook
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("es-US")
If Combo.SelectedValue.ToString().Trim() = "Something" Then
dgv.SelectAll()
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
Clipboard.SetDataObject(dgv.GetClipboardContent())
End If
appExcel = New Excel.Application
appExcel.SheetsInNewWorkbook = 1
wbExcel = appExcel.Workbooks.Add
appExcel.Visible = True
wbExcel.Worksheets(1).Range("A3").Select()
wbExcel.Worksheets(1).Paste()
我如何做这些事情并美化我导出的Excel?
提前致谢
答案 0 :(得分:1)
要设置单元格样式,可以创建Excel.Style并将其应用于范围。首先,您需要获得对工作表的引用,如:
Dim xlWorksheet As Excel.Worksheet = wbExcel.Worksheets(1)
然后创建样式:
Dim RptHeader As Excel.Style = xlWorksheet.Application.ActiveWorkbook.Styles.Add("RptHeader")
RptHeader.Font.Bold = True
RptHeader.Font.Size = 14
RptHeader.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSteelBlue)
RptHeader.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
然后设置范围/单元格的样式(对于范围,只需使用类似xlWorksheet.Range(“A1:A2”)。样式):
xlWorksheet.Cells(1, 1).Style = "RptHeader"
...对于单元格宽度/高度,基本语法如下:
xlWorksheet.Columns(1).EntireColumn.ColumnWidth = 25
xlWorksheet.Rows(1).RowHeight = 25
当你说列不是“正常调整”时,我觉得你在谈论自动调整,这也可以这样完成:
xlWorksheet.Range("A:XFD").EntireColumn.AutoFit()
要从datagridview添加不属于您副本的数据,只需将单元格的值设置为您想要的值:
xlWorkSheet.Cells(1, 2) = "1234" '1 being the row-index, 2 the column-index