儲存Word

世紀緣發表於2016-09-18
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

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

        private void button1_Click(object sender, EventArgs e)
        {

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = @"*.docx|*.docx";

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Task.WaitAll(task);
                doc.SaveAs2(sfd.FileName);
                MessageBox.Show("Success!");
            }

        }

        Task task;
        
        private void Form1_Load(object sender, EventArgs e)
        {
            task = Task.Factory.StartNew(new Action(() => { SaveDoc(); }));
        }

        Word.Document doc;

        private void SaveDoc()
        {
            List<room> rooms = new List<room>();

            using (SmallDemoDataContext cxt = new SmallDemoDataContext())
            {
                rooms = cxt.rooms.ToList();
            }

            Word.Application app = new Word.Application();
            doc = app.Documents.Add();

            app.Selection.Font.Bold = 10;
            app.Selection.Font.Size = 30;
            app.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            app.Selection.Text = "Room demo";

            app.Selection.Font.Size = 10;
            app.Selection.Font.Bold = 0;

            app.Selection.MoveDown();
            app.Selection.TypeParagraph();

            int count = rooms.Count + 1;

            Word.Table table = app.Selection.Tables.Add(app.Selection.Range, count, typeof(room).GetProperties().Count());
            table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;

            int current = 1;

            for (int i = 1; i <= typeof(room).GetProperties().Count(); i++)
            {
                table.Cell(current, i).Range.Text = typeof(room).GetProperties()[i - 1].Name.ToString();
            }

            current++;

            while (current <= count)
            {
                for (int i = 1; i <= typeof(room).GetProperties().Count(); i++)
                {
                    string text = typeof(room).GetProperty(typeof(room).GetProperties()[i - 1].Name.ToString()).GetValue(rooms[current - 2]).ToString();
                    table.Cell(current, i).Range.Text = text;
                }

                current++;
            }
        }
    }
}

相關文章