[英]OpenXML generate Report from Excel Model
我大家,我需要你的帮助来了解如何通过使用 Openxml 从模板复制来填充新的 excel。 我想保留从模板派生的列的格式;
Public Sub ExportDTfromModel(ByVal pathmodel As String, ByVal pathdestination As String, ByVal dt As System.Data.DataTable)
u.SegnalaSoloLog("Inizio Metodo: " & MethodBase.GetCurrentMethod().Name.ToString())
Try
If System.IO.File.Exists(pathmodel) Then
System.IO.File.Copy(pathmodel, pathdestination)
Using spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(pathdestination, True)
Dim WorksheetPart As WorksheetPart = GetWorksheetPartByName(spreadSheet, dt.TableName)
If (Not WorksheetPart Is Nothing) Then
Dim worksheet As Worksheet = New Worksheet()
WorksheetPart.Worksheet = worksheet
Dim sheetData As SheetData = New SheetData()
Dim headerRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
Dim columns As List(Of String) = New List(Of String)()
For Each column As DataColumn In dt.Columns
columns.Add(column.ColumnName)
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName)
' Dim headerCell As Cell = createTextCell(
'ds.Columns.IndexOf(column) + 1,
'1,
'column.ColumnName)
headerRow.AppendChild(cell)
Next
sheetData.AppendChild(headerRow)
'For i As Integer = 0 To ds.Rows.Count - 1
' Dim contentRow As DataRow
' contentRow = ds.Rows(i)
' sheetData.AppendChild(createContentRow(contentRow, i + 2))
'Next
For Each dsrow As DataRow In dt.Rows
Dim newRow As DocumentFormat.OpenXml.Spreadsheet.Row = New DocumentFormat.OpenXml.Spreadsheet.Row()
For Each col As String In columns
Dim cell As DocumentFormat.OpenXml.Spreadsheet.Cell = New DocumentFormat.OpenXml.Spreadsheet.Cell()
' cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
Select Case dsrow(col).GetType().ToString
Case "System.DateTime"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(Convert.ToDateTime(dsrow(col)))
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Date
Case "System.Decimal"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(Convert.ToDecimal(dsrow(col)))
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number
Case "System.String"
cell.CellValue = New DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow(col).ToString)
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String
End Select
newRow.AppendChild(cell)
Next
sheetData.AppendChild(newRow)
Next
End If
spreadSheet.WorkbookPart.Workbook.Save()
GC.Collect()
u.SegnalaSoloLog("File Excel Generato in : " & pathdestination)
End Using
Else
u.SegnalaSoloLog("Errore Modello non trovato, impossibile esportare il file")
End If
Catch ex As Exception
u.SegnalaSoloLog("Errore in Export from model: " & ex.Message)
End Try
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.