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

最近要做一个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文件(*.xlsx)|*.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表是我乱建的,与代码稍微有点不同,这个根据自己实际需求操作就行

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值