如何在打开的 XML 表中转换网格视图

本文关键字:转换 网格 视图 XML | 更新日期: 2023-09-27 18:36:58

我有一个 GridView,我想使用打开的 XML 表将其导出到 Word 文档中

var dt = FunctionThatReturnDataTable(id);            
var gd = new GridView
             {
                DataSource = dt,
                AutoGenerateColumns = true
             };

我创建了一个word文档并在其中插入了一个段落,现在我想在下面添加我的网格视图

using (var myDoc = WordprocessingDocument.Create(@"c:test.doc",
                                    WordprocessingDocumentType.Document))
{                    
  MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
  mainPart.Document = new Document();
  var body = new Body();
  var p = new Paragraph(new ParagraphProperties(
             new Justification() { Val = JustificationValues.Center }), 
                           new Run(new Text("Some Text")));
  body.Append(p);
  mainPart.Document.Append(body);
  mainPart.Document.Save();
}

如何在打开的 XML 表中转换网格视图

我可以想到两种不同的导出方法Word 文档的 ASP.Net GridView

第一种方法将GridView控件的 HTML 呈现为内存流,然后使用 OpenXML altChunk元素导入将 HTML 生成到 Word 文档中。简而言之,altChunk标记元素指示 MS Word 将内容(例如.HTML)导入到公文。有关示例,请参阅以下代码:

...
var p = new Paragraph(new ParagraphProperties(
         new Justification() { Val = JustificationValues.Center }), 
                       new Run(new Text("Some Text")));
body.Append(p);
mainPart.Document.Append(body);
// Add table to word document using alt chunk element.  
AddTableUsingAltChunk(gv, mainPart);
...
public static void AddTableUsingAltChunk(GridView gv, MainDocumentPart mainPart)
{
  MemoryStream ms = new MemoryStream();
  StreamWriter sw = new StreamWriter(ms, Encoding.UTF8);
  using (HtmlTextWriter htw = new HtmlTextWriter(sw))
  {
    gv.RenderControl(htw);  // Render HTML of GridView
    htw.Flush();
    string altChunkId = "myChunkId";
    // Create alternative format import part.
    AlternativeFormatImportPart formatImportPart = 
     mainPart.AddAlternativeFormatImportPart(
        AlternativeFormatImportPartType.Xhtml, altChunkId);
    ms.Seek(0, SeekOrigin.Begin);
    // Feed HTML data into format import part (chunk).
    formatImportPart.FeedData(ms);
    AltChunk altChunk = new AltChunk();
    altChunk.Id = altChunkId;    
    // Append chunk.
    mainPart.Document.Body.Append(altChunk);    
  }
}

第二种方法更为复杂。我们使用 openxml SDK 提供的类来生成表。有关进一步说明,请参阅以下代码和内联注释。

var dt = FunctionThatReturnDataTable(id)
...
var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
  new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties(
           new Justification() { Val = JustificationValues.Center }),
                         new DocumentFormat.OpenXml.Wordprocessing.Run(new Text("Some Text")));
body.Append(p);
mainPart.Document.Append(body);
mainPart.Document.Body.Append(CreateTable(dt));    
...
// Creates an open xml table from the provided data table.
public static Table CreateTable(System.Data.DataTable dt)
{
  Table table = new Table();
  TableProperties tableProperties = new TableProperties();
  TableStyle tableStyle = new TableStyle() { Val = "MyStyle" };
  TableWidth tableWidth = new TableWidth() 
   { 
     Width = "0", 
     Type = TableWidthUnitValues.Auto 
   };
  TableLook tableLook = new TableLook() { Val = "04A0" };
  tableProperties.Append(tableStyle);
  tableProperties.Append(tableWidth);
  tableProperties.Append(tableLook);
  TableGrid tableGrid = new TableGrid();
  // Calculate column width in twentieths of a point (same width for every column).
  // 595=A4 paper width in points.
  int colWidth = (int)((595 / (float)dt.Columns.Count) * 20.0f);
  // Create columns
  foreach (DataColumn dc in dt.Columns)
  {
    tableGrid.Append(new GridColumn() { Width = colWidth.ToString() });
  }  
  table.Append(tableProperties);
  table.Append(tableGrid);
  // Create rows.
  foreach (DataRow dr in dt.Rows)
  {
    TableRow tableRow = new TableRow() 
     { 
       RsidTableRowAddition = "00C5307B", 
       RsidTableRowProperties = "00C5307B" 
     };
    // Create cells.
    foreach (object c in dr.ItemArray)
    {
      TableCell tableCell = new TableCell();
      TableCellProperties tableCellProperties = new TableCellProperties();
      TableCellWidth tableCellWidth = new TableCellWidth() 
        { 
          Width = colWidth.ToString(), 
          Type = TableWidthUnitValues.Dxa 
        };
      tableCellProperties.Append(tableCellWidth);
      Paragraph paragraph = new Paragraph() 
           { 
             RsidParagraphAddition = "00CC797A", 
             RsidRunAdditionDefault = "00CC797A" 
           };
      Run run = new Run();
      Text text = new Text();
      text.Text = c.ToString();
      run.Append(text);
      paragraph.Append(run);
      tableCell.Append(tableCellProperties);
      tableCell.Append(paragraph);
      tableRow.Append(tableCell);
    }
    table.Append(tableRow);
  }
  return table;
}

两种方法生成的 xml 大不相同。使用 OpenXML SDK 生产力工具等工具查看生成的 xml。在altChunk情况下,您不会在生成的 xml 中看到表的定义。