C#读取word表格保存到sql

//C#读取word表格保存到sql
//部分代码为网上搜集,需引用MSWORD.OLD
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;
using System.Data;
using System.Globalization;
using System.Data.SqlClient;
using System.Data.OleDb;
using Microsoft.VisualBasic;
namespace cWord
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //AutoScale();
        }
        ///     
        ///   不让之拖动标题栏  
        ///  
  
        ///     
        //protected override void WndProc(ref   Message m)
        //{
        //    base.WndProc(ref   m);
        //    if (m.Msg == 0x84)     //不让拖动标题栏  
        //    {
        //        if ((IntPtr)2 == m.Result)
        //            m.Result = (IntPtr)1;
        //    }
        //    if (m.Msg == 0x00A3)       //双击标题栏无反应  
        //        m.WParam = System.IntPtr.Zero;
        //}
        protected override void OnResize(EventArgs e)
        {
            if (WindowState == FormWindowState.Maximized)
            {
                //最大化时所需的操作
                grid2.Height = this.Height - 100;
                grid1.Height = this.Height - 100;

                grid1.Width  = this.Width  - 300;
                //MessageBox.Show(this.Height.ToString() );
            }
            else if (WindowState == FormWindowState.Minimized)
            {
                //最小化时所需的操作
                //MessageBox.Show("min");
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //object oMissing = System.Reflection.Missing.Value;
            grid2.Rows = 2;
            grid2.Cols = 3;
            grid2.Cell(0, 0).Text = "序号";
            grid2.Cell(0, 1).Text = "文件名称";
            grid2.Cell(0, 2).Text = "状态";
            grid2.Column(2).AutoFit();
            grid2.Column(1).Locked = true;
            grid2.Column(2).Locked = true;
            grid2.DisplayRowNumber = true;
            grid1.Rows = 2;
            grid1.Cols = 13;
            for (int i=0; i+1<=grid1.Cols ; i++)
            {
                grid1.Column(i).Locked = true;
            }



            grid1.Cell(0, 1).Text = "用户";
            grid1.Cell(0, 2).Text = "品种";
            grid1.Cell(0, 3).Text = "孔径1";
            grid1.Cell(0, 4).Text = "孔径2";
            grid1.Cell(0, 5).Text = "孔径3";
            grid1.Cell(0, 6).Text = "砖坯图号";
            grid1.Cell(0, 7).Text = "成品图号";
            grid1.Cell(0, 8).Text = "工艺路线";
            grid1.Cell(0, 9).Text = "冷加工工序及要求";
            grid1.Cell(0, 10).Text = "错误记录";
            grid1.Cell(0, 11).Text = "文件名称";
            grid1.Cell(0, 12).Text = "客户编号";
            grid1.DisplayRowNumber = true;
            // Microsoft.Office.Interop.Word._Application oWord=new Microsoft.Office.Interop.Word._Application ();
            //oWord.Visible =true ;//设置Word应用程序为可见

        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            grid1.AutoRedraw = false;
            for (int i = 1; i + 1 <= grid2.Rows; i++)
            {
               
                object fileName = textBox1.Text.ToString() + grid2.Cell(i, 1).Text.ToString();
                //object fileName=listView1.Items.Find(i) ;
                object readOnly = true;
                object isVisible = false;
                object missing = System.Reflection.Missing.Value;
               
                Microsoft.Office.Interop.Word.ApplicationClass oWordApp = new ApplicationClass();
              
                Microsoft.Office.Interop.Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName, ref missing, ref readOnly,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

                oWordDoc.Activate();

                //int i = oWordDoc.Tables.Count;    //文文件中表格的个数
                //try
                //{
                    Microsoft.Office.Interop.Word.Table nowTable = oWordDoc.Tables[1];
                //}
                //catch
                //{
                //    System.Windows.Forms.MessageBox.Show("doc文档错误!");
                //}
                //Word.Table nowTable = oWordDoc.Tables[1];    //文文件中第一个表格

                //读取表格内容

                //for (int k = 1; k <= nowTable.Rows.Count ; k++)
                //{
                //    for (int l = 1; l <= nowTable.Columns.Count ; l++)
                //    {
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 1).Text = nowTable.Cell(1, 2).Range.Text.Substring(0, nowTable.Cell(1, 2).Range.Text.Length - 1).Replace(" ", "");
                            //System.Windows.Forms.MessageBox.Show(grid1.Cell(grid1.Rows - 1, 1).Text.ToString ());
 
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (1,2)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 2).Text = nowTable.Cell(2, 2).Range.Text.Substring(0, nowTable.Cell(2, 2).Range.Text.Length - 1).Replace(" ", "");
                            //System.Windows.Forms.MessageBox.Show(grid1.Cell(grid1.Rows - 1, 2).Text.ToString());
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (2,2)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 3).Text = nowTable.Cell(6, 2).Range.Text.Substring(0, nowTable.Cell(6, 2).Range.Text.Length - 1).Replace("φ", "");
                            //System.Windows.Forms.MessageBox.Show(grid1.Cell(grid1.Rows - 1, 3).Text.ToString());
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (6,8)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 4).Text = nowTable.Cell(7, 2).Range.Text.Substring(0, nowTable.Cell(7, 2).Range.Text.Length - 1).Replace("φ", "");
                            //System.Windows.Forms.MessageBox.Show(grid1.Cell(grid1.Rows - 1, 4).Text.ToString());
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (7,2)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 5).Text = nowTable.Cell(8, 2).Range.Text.Substring(0, nowTable.Cell(8, 2).Range.Text.Length - 1).Replace("φ", "");
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (8,2)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 6).Text = nowTable.Cell(1, 8).Range.Text.Substring(0, nowTable.Cell(1, 8).Range.Text.Length - 1).Replace(" ", "");
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (1,8)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 7).Text = nowTable.Cell(2, 8).Range.Text.Substring(0, nowTable.Cell(2, 8).Range.Text.Length - 1).Replace(" ", "");
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (2,8)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 8).Text = nowTable.Cell(3, 2).Range.Text.Substring(0, nowTable.Cell(3, 2).Range.Text.Length - 1).Replace(" ", "");
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (3,2)读取错误!";
                        }
                        try
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = nowTable.Cell(nowTable.Rows.Count - 1, 2).Range.Text.Substring(0, nowTable.Cell(nowTable.Rows.Count - 1, 2).Range.Text.Length - 1).Replace(" ", "");
                        }
                        catch
                        {
                            grid1.Cell(grid1.Rows - 1, 9).Text = grid1.Cell(grid1.Rows - 1, 9).Text.ToString() + "  (rows-2,2)读取错误!";
                        }
                        grid1.Cell(grid1.Rows - 1, 11).Text = grid2.Cell(i, 1).Text.ToString();

                //关闭
                oWordApp.Application.Quit(ref missing, ref missing, ref missing);
                //回收垃圾
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);
                grid1.Rows = grid1.Rows + 1;
                grid2.Cell(i, 2).Text = "ok";
            }
          
            for (int k = 1; k <= grid1.Rows - 2; k++)
            {
                for (int i = 1; i + 1 <= grid1.Cols; i++)
                {
                    grid1.Cell(k, i).Text =convertNarrow( DelKG(grid1.Cell(k, i).Text.ToString()));
                }
            }
            for (int i = 1; i + 1 <= grid1.Cols; i++)
            {//自动列宽
                grid1.Column(i).AutoFit();
            }
            grid1.AutoRedraw = true;
            grid1.Refresh();
        }
        private string DelKG(string str)
        {//替换回车符
            str = str.Replace("/r", "");
            return str;
        }
        private string convertNarrow(string str)
        {//全角转半角
            str = Strings.StrConv(str, VbStrConv.Narrow, 0);
            return str;
        }
       
        private void button2_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Title = "导出到Excel";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            saveFileDialog1.ShowDialog();
            if (saveFileDialog1.FileName.Replace(" ","").Length == 0)
            {
           
            }
            else
            {
                grid1.ExportToExcel(saveFileDialog1.FileName.ToString(), true, true);
                System.Windows.Forms.MessageBox.Show("当前数据已经保存到 " + saveFileDialog1.FileName.ToString());
            }
            //folderBrowserDialog1.SelectedPath;
            // System.Diagnostics.Process.Start(@"explorer C:/Windows");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //获取指定目录下的文件名

            //方法一  字符串
            //string CurrentDir = @"E://产品工艺卡";//Directory.GetCurrentDirectory();
            //string[] CurrentFiles = Directory.GetFiles(CurrentDir);
            //foreach (string cf in CurrentFiles)
            //{
            //    Console.WriteLine(cf);//输入带路径的文件名,字符串方式
            //}
            //方法二  对象
            if (textBox1.Text.Length > 0)
            {
                int i = 1;
                grid2.AutoRedraw = false;
                grid2.Rows = 2;
                DirectoryInfo info = new DirectoryInfo(textBox1.Text.ToString());
                foreach (FileInfo file in info.GetFiles("*.doc"))
                {
                    grid2.Cell(i, 1).Text = file.Name;
                    grid2.Cell(i, 2).Text =null ;
                    grid2.Rows = grid2.Rows + 1;
                    //listView1.Items.Add(file.Name, i);
                    i = i + 1;
                    //listView1.Items.Count.ToString(); //列表框总条数
                    //   Console.WriteLine(file.Name);
                }
                grid2.RemoveItem(grid2.Rows - 1);
                grid2.AutoRedraw = true;
                grid2.Refresh();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("请设置文件路径!");
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {

            this.Close();
        }
        //获取打开文件的文件名(包括文件的扩展名)
        //注意:参数FileName为OpenFileDialog.FileName
        public string GetFileName(string FileName)
        {
            string[] Names = FileName.Split(new char[] { '//' });
            string Name = Names[Names.Length - 1];
            return Name;
        }
        //获取打开文件的路径
        //注意:参数FileName为OpenFileDialog.FileName
        public string GetPath(string FileName)
        {
            string path = FileName.Replace(GetFileName(FileName), "");
            return path;
        }
        public string GetPName(string FileName)
        {
            string[] Names = FileName.Split(new char[] { '//' });
            string Name = Names[Names.Length - 1];
            return Name;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            textBox1.Text = GetPath(openFileDialog1.FileName.ToString());
            int i = 1;
            grid2.AutoRedraw = false;
            grid2.Rows = 2;
            if (textBox1.Text.Length > 0)
            {
                DirectoryInfo info = new DirectoryInfo(textBox1.Text.ToString());
                foreach (FileInfo file in info.GetFiles("*.doc"))
                {
                    grid2.Cell(i, 1).Text = file.Name;
                    grid2.Cell(i, 2).Text = null ;
                    grid2.Rows = grid2.Rows + 1;
                 
                    //grid2.Tag = GetPName(textBox1.Text.Substring(0,textBox1.Text.Length -2).ToString()).Substring(0,3).ToString();//返回客户文件夹名称前三位
                   
                    //listView1.Items.Add(file.Name, i);
                    i = i + 1;
                    //listView1.Items.Count.ToString(); //列表框总条数
                    //   Console.WriteLine(file.Name);
                }
                grid2.RemoveItem(grid2.Rows - 1);
                grid2.AutoRedraw = true;
                grid2.Refresh();
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            for (int i = 0; i + 1 <= grid1.Cols; i++)
            {
                grid1.Column(i).Locked =false ;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            grid1.Rows = 2;
            grid2.Rows = 2;
            for (int i = 1; i <= grid1.Cols - 1; i++)
            {
                grid1.Cell(1, i).Text = null;
                if (i <= 2)
                {
                    grid2.Cell(1, i).Text = null;
                }
            }
        }

 

        private void button9_Click(object sender, EventArgs e)
        {
            grid1.RemoveItem(grid1.Rows - 1);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            DataTable auto = new DataTable("Auto");//创建对象
            DataColumn 用户名称 = new DataColumn("用户名称");//创建列,列名必须与数据库表列名称一致
            用户名称.DataType = typeof(string);//列数据类型
            用户名称.MaxLength = 50;//列长度
            用户名称.Unique = false;//是否唯一
            用户名称.AllowDBNull = false;//是否允许空值
            用户名称.Caption = "用户名称";//列标题
            DataColumn 产品类别 = new DataColumn("产品类别");
            DataColumn 孔径1 = new DataColumn("孔径1");
            DataColumn 孔径2 = new DataColumn("孔径2");
            DataColumn 孔径3 = new DataColumn("孔径3");
            DataColumn 砖坯图号 = new DataColumn("砖坯图号");
            DataColumn 成品图号 = new DataColumn("成品图号");
            DataColumn 工艺路线 = new DataColumn("工艺路线");
            DataColumn 冷加工工序 = new DataColumn("冷加工工序");
            DataColumn 错误记录 = new DataColumn("错误记录");
            DataColumn 文件名称 = new DataColumn("文件名称");
            auto.Columns.Add(用户名称);
            auto.Columns.Add(产品类别);
            auto.Columns.Add(孔径1 );
            auto.Columns.Add(孔径2 );
            auto.Columns.Add(孔径3 );
            auto.Columns.Add(砖坯图号 );
            auto.Columns.Add(成品图号 );
            auto.Columns.Add(工艺路线 );
            auto.Columns.Add(冷加工工序 );
            auto.Columns.Add(错误记录 );
            auto.Columns.Add(文件名称 );
            auto.Columns.Add(客户编号);
            //, 产品类别, 孔径1, 孔径2, 孔径3, 砖坯图号, 成品图号, 工艺路线, 冷加工工序, 错误记录, 文件名称
            for (int i = 1; i <= grid1.Rows - 2; i++)
            {
                auto.Rows.Add(grid1.Cell(i, 1).Text, grid1.Cell(i, 2).Text, grid1.Cell(i, 3).Text, grid1.Cell(i, 4).Text, grid1.Cell(i, 5).Text, grid1.Cell(i, 6).Text, grid1.Cell(i, 7).Text, grid1.Cell(i, 8).Text, grid1.Cell(i, 9).Text, grid1.Cell(i,10).Text, grid1.Cell(i, 11).Text, grid1.Cell(i, 12).Text);//添加DataRow对象
            }
            string cnn = "server=192.168.*.*;database=**;user id=*; password=*;";
            auto.TableName = "tmp产品信息";
            SqlConnection conn = new SqlConnection(cnn);
            string sqlstr = "select * from tmp产品信息";
            SqlDataAdapter  da = new SqlDataAdapter(sqlstr, conn);
            SqlCommandBuilder cb = new SqlCommandBuilder(da);
            DataSet ds = new DataSet();
            da.Fill(ds, "tmp产品信息");
            ds.Tables["tmp产品信息"].Merge(auto);//auto即内存表
            da.Update(ds, "tmp产品信息");
            ds.AcceptChanges();
            conn.Close();
            System.Windows.Forms.MessageBox.Show("保存成功");
            grid1.Rows = 2;
            grid2.Rows = 2;
            for (int i = 1; i <= grid1.Cols - 1; i++)
            {
                grid1.Cell(1, i).Text = null;
                if (i <= 2)
                {
                    grid2.Cell(1, i).Text = null;
                }
            }
        }


        private void grid1_Load(object sender, EventArgs e)
        {

        }

    }
}

你可能感兴趣的:(c#,textbox,string,object,button,dataset)