Esempio n. 1
0
 private void toolStripLabel3_Click(object sender, EventArgs e)
 {
     try
     {
         DialogResult queren = MessageBox.Show("读取的'EXCEL文件'后缀必须为.Xlsx,否则读取失败!", "系统提示!", MessageBoxButtons.YesNo);
         if (queren == DialogResult.Yes)
         {
             this.backgroundWorker1.RunWorkerAsync();
             JingDu form = new JingDu(this.backgroundWorker1, "读取中");// 显示进度条窗体
             form.ShowDialog(this);
             form.Close();
             if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 string path = openFileDialog1.FileName;
                 if (!path.Equals(string.Empty))
                 {
                     if (!File.Exists(path))
                     {
                         MessageBox.Show("文件不存在!");
                         return;
                     }
                     IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);
                     if (vHandle == HFILE_ERROR)
                     {
                         MessageBox.Show("文件被占用!");
                         return;
                     }
                     CloseHandle(vHandle);
                     if (path.Trim().Contains("xlsx"))
                     {
                         List <KuCun> list = cal.readerKucunExcel(path);
                         DataTable    dt   = new DataTable();
                         dt.Columns.Add("Id", typeof(int));
                         for (int i = 0; i < dataGridView1.Columns.Count; i++)
                         {
                             if (!dataGridView1.Columns[i].HeaderCell.Value.ToString().Equals("Id"))
                             {
                                 dt.Columns.Add(dataGridView1.Columns[i].HeaderCell.Value.ToString(), typeof(String));
                             }
                         }
                         foreach (KuCun s in list)
                         {
                             dt.Rows.Add(s.Id, s.PingMing, s.HuoHao, s.SeHao, s.ShuLiang, s.GongHuoFang, s.CunFangDI);
                         }
                         dataGridView1.DataSource = dt;
                         MessageBox.Show("读取完成!");
                     }
                     else
                     {
                         MessageBox.Show("读取失败!原因:读取文件后缀非'xlsx'");
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }