您的位置:首页 > 编程语言 > C#

Excel在C#中的导入导出,并对值进行简单修改

2016-06-16 08:51 411 查看
最近要做一个Excel在C#winform中的导入导出,经过两天时间(本人菜鸟一只刚接触C#)终于做好了,现在与大家分享下

public partial class Form1 : Form

    {

        //private SerialPort sp;

        private DataTable dt;

        public Form1()

        {

            InitializeComponent();

        }

        public void ImportExcel(string excelName,string tableName){

            string strcon = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + excelName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";//连接excel文件的字符串

            if (excelName == null)

            {

                return;

            }

            OleDbConnection con = new OleDbConnection(strcon);//建立连接

            con.Open();//打开连接

            OleDbDataAdapter oda = new OleDbDataAdapter("select * from" + tableName, con);

            DataSet ds = new DataSet();

            try

            {

                oda.Fill(ds,"Sheet1");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

 if (ds != null)

            {

                dt = ds.Tables[0];

                this.dataGridView1.DataSource = dt;

            }

            else

            {

                MessageBox.Show("没有数据");

            }

            con.Close();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            textBox2.Focus();

            serialPort1.Open();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.DefaultExt = "xlsx";

            ofd.Filter = "Excel文件(*.xl
96ea
sx)|*.xlsx";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

            {

                this.textBox1.Text = ofd.FileName.ToString();

                ImportExcel(ofd.FileName, "[Sheet1$]");//传递excel文件名和表名

                

            }

        }

 public bool ExportDataGridView(DataGridView gridView, bool isShowExcel)// gridView (DataGridView对象),bool isShowExcel(是否显示Excel) 

        {

            if (gridView.Rows.Count == 0)

                return false;

            //创建Excel对象

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            excel.Application.Workbooks.Add(true);

            excel.Visible = isShowExcel;

            //生成字段的名称

            for (int i = 0; i < gridView.ColumnCount; i++)

            {

                excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;

            }

            //填充数据

            for (int i = 0; i < gridView.RowCount; i++)

            {

                for (int j = 0; j < gridView.ColumnCount; j++)

                {

                    if (gridView[j, i].Value!= null)

                    {

                        if (gridView[j, i].ValueType == typeof(string))

                        {

                            excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();

                        }

                        else

                        {

                             excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();

                        }

                    }

                    else

                    {

                        gridView[j, i].Value = "";

                    }

                }

            }

            return true;

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (!ExportDataGridView(dataGridView1, true))

            {

                MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }

           

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)   //串口实现(利用扫描枪)

        {

            String str = serialPort1.ReadTo("\r\t");

            DoCheck(str);

        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)  //textbox2输入(usb)

        {

            if (e.KeyData == Keys.Enter)

            {

                DoCheck(textBox2.Text);

            }

        }

        private void DoCheck(String str) //改变勾选值

        {

            string[] array = str.Split(',');

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                if (dt.Rows[i][1] != null && dt.Rows[i][2] != null)

                {

                    if (array[2] == dt.Rows[i][1].ToString() && array[3] == dt.Rows[i][2].ToString())

                    {

                        if (dt.Rows[i][0].ToString() == "是")

                        {

                            MessageBox.Show("重复勾选", "温馨提示", MessageBoxButtons.OKCancel);

                        }

                        else

                        {

                            dt.Rows[i][0] = "是";

                        }

                    }

                }

            }

            dataGridView1.DataSource = dt;

            textBox2.Focus();

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            serialPort1.Close();  

        }

    }   

效果如图所示,Excel表是我乱建的,与代码稍微有点不同,这个根据自己实际需求操作就行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel c#