using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Ex05_9
{
    public partial class Form1 : Form
    {
        SqlConnection sqlcon = new SqlConnection("server=(local);user id=myzf;pwd=123456;database=MysqlData");
        SqlDataAdapter myda;
        DataSet myds;

        public bool ExportDataGridview(DataGridView dgv, bool isShowWord)
        {
            Word.Document mydoc = new Word.Document();
            Word.Table mytable;
            Word.Selection mysel;
            Object myobj;
            if (dgv.Rows.Count == 0)
                return false;
            //建立Word对象
            Word.Application word = new Word.Application();
            myobj = System.Reflection.Missing.Value;
            mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
            word.Visible = isShowWord;
            mydoc.Select();
            mysel = word.Selection;
            //将数据生成Word表格文件
            mytable = mydoc.Tables.Add(mysel.Range, dgv.RowCount, dgv.ColumnCount, ref myobj, ref myobj);
            //设置列宽
            mytable.Columns.SetWidth(30, Word.WdRulerStyle.wdAdjustNone);
            //输出列标题数据
            for (int i = 0; i < dgv.ColumnCount; i++)
            {
                mytable.Cell(1, i + 1).Range.InsertAfter(dgv.Columns[i].HeaderText);
            }
            //输出控件中的记录
            for (int i = 0; i < dgv.RowCount - 1; i++)
            {
                for (int j = 0; j < dgv.ColumnCount; j++)
                {
                    mytable.Cell(i + 2, j + 1).Range.InsertAfter(dgv[j, i].Value.ToString());
                }
            }
            return true;
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportDataGridview(dataGridView1, true);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myda = new SqlDataAdapter("select * from 应付账", sqlcon);
            myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds);
            sqlcon.Close();
            dataGridView1.DataSource = myds.Tables[0];
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
