使用标题创建Excel表

时间:2015-10-19 13:39:58

标签: excel vb.net openxml

我使用OpenXML编写了一个代码,用于将数据表转换为Excel。现在我想格式化表格,使其看起来像带有标题的Excel表格。我假设我需要添加标题样式并设置表范围,但我仍然无法实现。这是我从datatable转换为Excel的代码:

Dim oData As New ReportData(_ReportObject.ConnectionString)
Dim source As DataTable = oData.GetDataTable(_ReportObject.DataSource, _ReportObject.Parameters)
Dim cellData As Object

Dim draftFile As String = _ReportObject.Tmp & "\" & Guid.NewGuid().ToString() & ".tmp"
Using xl As SpreadsheetDocument = SpreadsheetDocument.Create(draftFile, SpreadsheetDocumentType.Workbook)
  Dim oxa As List(Of OpenXmlAttribute)
  Dim oxw As OpenXmlWriter

  xl.AddWorkbookPart()
  Dim wsp As WorksheetPart = xl.WorkbookPart.AddNewPart(Of WorksheetPart)()

  oxw = OpenXmlWriter.Create(wsp)
  oxw.WriteStartElement(New Worksheet())
  oxw.WriteStartElement(New SheetData())

  ' add header
  oxa = New List(Of OpenXmlAttribute)()
  oxa.Add(New OpenXmlAttribute("r", Nothing, "1"))
  oxw.WriteStartElement(New Row(), oxa)
  For Each header As DataColumn In source.Columns
    oxa = New List(Of OpenXmlAttribute)()
    oxa.Add(New OpenXmlAttribute("t", Nothing, "str"))
    oxw.WriteStartElement(New Cell(), oxa)
    oxw.WriteElement(New CellValue(header.Caption))
    oxw.WriteEndElement()
  Next
  oxw.WriteEndElement()

  For i As Integer = 0 To source.Rows.Count - 1
    Dim rowData As DataRow = source.Rows(i)
    oxa = New List(Of OpenXmlAttribute)()
    ' this is the row index
    oxa.Add(New OpenXmlAttribute("r", Nothing, (i + 2).ToString()))

    oxw.WriteStartElement(New Row(), oxa)

    For j As Integer = 0 To source.Columns.Count - 1
      oxa = New List(Of OpenXmlAttribute)()
      oxa.Add(New OpenXmlAttribute("t", Nothing, "str"))

      oxw.WriteStartElement(New Cell(), oxa)

      cellData = rowData(j)
      If IsDBNull(cellData) Then cellData = String.Empty
      oxw.WriteElement(New CellValue(cellData))

      ' this is for Cell
      oxw.WriteEndElement()
    Next

    ' this is for Row
    oxw.WriteEndElement()
  Next

  ' this is for SheetData
  oxw.WriteEndElement()
  ' this is for Worksheet
  oxw.WriteEndElement()
  oxw.Close()

  oxw = OpenXmlWriter.Create(xl.WorkbookPart)
  oxw.WriteStartElement(New Workbook())
  oxw.WriteStartElement(New Sheets())

  Dim sheet As New Sheet()
  sheet.Name = "Sheet1"
  sheet.SheetId = 1
  sheet.Id = xl.WorkbookPart.GetIdOfPart(wsp)
  oxw.WriteElement(sheet)

  ' this is for Sheets
  oxw.WriteEndElement()
  ' this is for Workbook
  oxw.WriteEndElement()
  oxw.Close()

  xl.Close()
End Using

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码手动输入:

Sheet.Cells(1, 1).value = "Header for cell A1"
Sheet.Cells(1, 2).value = "Header for cell B1"
Sheet.Cells(1, 3).value = "Header for cell C1"

CMIIW:)