繁体   English   中英

如何将整个datagridview导出成word文档(在C#中使用office word interop DLL)

[英]How to export the entire datagridview into a word document (using office word interop DLL in C#)

如何使用 office word interop DLL 更新/写入/保存/导出整个 DataTable 或 datagridview 到同一个 word 文档中(多次)?我能够实现它,但问题是我无法将 DataTable 保存到单个文档中,每次它都会保存因为新文档不会保存在以前的文档中。 `使用系统; 使用 System.Collections.Generic; 使用 System.ComponentModel; 使用 System.Data; 使用 System.Drawing; 使用 System.Linq; 使用 System.Text; 使用 System.Windows.Forms; 使用 System.IO; 使用 Word = Microsoft.Office.Interop.Word; 使用 System.Reflection;

namespace Save_DataTable
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public string data_path;
    public string File_path;
    public string filename;

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("x",            
   typeof(int)), new DataColumn("y", typeof(string)), new   
   DataColumn("z",  
   typeof(string)) });
        dt.Rows.Add(1, "1", "1");
        dt.Rows.Add(2, "2", "2");
        dt.Rows.Add(3, "3", "3");
        dt.Rows.Add(4, "4", "4");
        this.dataGridView1.DataSource = dt;
    }

    private void Save()
    {
        if (dataGridView1.Rows.Count != 0)
        {
            int RowCount = dataGridView1.Rows.Count;
            int ColumnCount = dataGridView1.Columns.Count;
            Object[,] DataArray = new object[RowCount + 1, ColumnCount 
       + 
        1];

            //add rows
            int r = 0;
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                for (r = 0; r <= RowCount - 1; r++)
                {
                    DataArray[r, c] = 
       dataGridView1.Rows[r].Cells[c].Value;
                } //end row loop
            } //end column loop

            Word.Document oDoc = new Word.Document();
            //oDoc.Application.Visible = false;

            Word.Application app = new Word.Application();

            app.Application.Visible = false;

            try
            {
                oDoc = app.Documents.Open(filename);

            }
            catch
            {
            }
            //page orintation
            oDoc.PageSetup.Orientation = 
          Word.WdOrientation.wdOrientLandscape;


            dynamic oRange = oDoc.Content.Application.Selection.Range;
            string oTemp = "";
            for (r = 0; r <= RowCount - 1; r++)
            {
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oTemp = oTemp + DataArray[r, c] + "\t";

                }
            }

            //table format
            oRange.Text = oTemp;

            object Separator =  
         Word.WdTableFieldSeparator.wdSeparateByTabs;
            object ApplyBorders = true;
            object AutoFit = true;
            object AutoFitBehavior = 
         Word.WdAutoFitBehavior.wdAutoFitContent;

            oRange.ConvertToTable(ref Separator, ref RowCount, ref 
            ColumnCount,
                                  Type.Missing, Type.Missing, ref 
             ApplyBorders,
                                  Type.Missing, Type.Missing, 
             Type.Missing,
                                  Type.Missing, Type.Missing, 
              Type.Missing,
                                  Type.Missing, ref AutoFit, ref 
              AutoFitBehavior, Type.Missing);

            oRange.Select();

            oDoc.Application.Selection.Tables[1].Select();


        oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages 
        = 0;
            oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.InsertRowsAbove(1);
            oDoc.Application.Selection.Tables[1].Rows[1].Select();

            //header row style
            oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 
            1;

           oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name 
           = "Tahoma";

          oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size 
         = 14;

            //add header row manually
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                oDoc.Application.Selection.Tables[1].Cell(1, c + 
       1).Range.Text = dataGridView1.Columns[c].HeaderText;
            }

            //table style
            oDoc.Application.Selection.Tables[1].set_Style("Grid Table 
        4 - Accent 5");
            oDoc.Application.Selection.Tables[1].Rows[1].Select();
            oDoc.Application.Selection.Cells.VerticalAlignment = 
          Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            //header text
            foreach (Word.Section section in 
         oDoc.Application.ActiveDocument.Sections)
            {
                Word.Range headerRange = 
         section.Headers[Word.WdHeaderFooterIndex.
                      wdHeaderFooterPrimary].Range;
                headerRange.Fields.Add(headerRange, 
            Word.WdFieldType.wdFieldPage);
                headerRange.Text = "Header Text";
                headerRange.Font.Size = 16;
                headerRange.ParagraphFormat.Alignment =  
            Word.WdParagraphAlignment.wdAlignParagraphCenter;
            }
            oDoc.Activate();
            filename = @"D:\\Save.docx";
            oDoc.SaveAs2(filename);
            oDoc.Close();
            app.Quit();
        }
         }
      private void button1_Click(object sender, EventArgs e)
      {
        Save();
      }
       }
          }`

我建议使用 Open XML SDK 根据您的数据网格视图动态生成 W​​ord 文档(开放 XML 文档)。 有关详细信息,请参阅 欢迎使用适用于 Office 的 Open XML SDK 2.5

从其他应用程序自动化 Word 可能需要更多时间,并具有以下限制:

Microsoft 当前不建议也不支持从任何无人参与的非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)自动化 Microsoft Office 应用程序,因为 Office 可能表现出不稳定的行为和/或在此环境中运行 Office 时出现死锁。

如果您正在构建一个在服务器端上下文中运行的解决方案,您应该尝试使用已为无人值守执行安全的组件。 或者,您应该尝试找到至少允许部分代码在客户端运行的替代方案。 如果您使用服务器端解决方案中的 Office 应用程序,该应用程序将缺乏许多成功运行所需的功能。 此外,您将承担整体解决方案稳定性的风险。

Office 服务器端自动化注意事项一文中阅读有关此内容的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM