1

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

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

我创建了一个word文档并在里面插入了一个段落,现在我想在下面添加我的gridview

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();
}
4

1 回答 1

2

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

第一种方法将GridView控件的 HTML 渲染到内存流中,然后使用 openxmlaltChunk元素将生成的 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 Productivity 工具之类的工具来查看生成的 xml。如果altChunk您在生成的 xml 中看不到表的定义。

于 2012-06-18T19:36:52.293 回答