回复 3楼 god_hz
private void btnOpenRecord_Click(object sender, EventArgs e)//打开EXCEL文件
{
string str = @":\C";
ofdExcel.InitialDirectory = str;
string filter = "EXCEL文件(*.xls)|*.xls";
ofdExcel.Filter = filter;
app=new Excel.Application();
if (ofdExcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
RecordFile = ofdExcel.FileName;
lblRecordName.Text = RecordFile.ToString();//得到打开文件的名称
strTableNames = GetExcelTableNames(RecordFile);//得到工作表名称
tableNamesArray = strTableNames.Split(',');
int i = tableNamesArray.Length;
cboField.Items.Clear();
cboSheet.Items.Clear();
for(int j=0;j<i;j++)
cboSheet.Items.Add(tableNamesArray[j]);
//打开话单得到记录集
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RecordFile + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = null;
DataSet ds = new DataSet();
try
{
strExcel = "select * from [" + tableNamesArray[0] + "]";
conn.Open();
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds,"dsf");
dgvRecord.DataSource = ds.Tables["dsf"];
//字段数和记录数显示到标签,读取字段名称
lblFieldNumber.Text=ds.Tables["dsf"].Columns.Count.ToString();
lblRecordNumber.Text = ds.Tables["dsf"].Rows.Count.ToString();
for (int j = 0; j < ds.Tables["dsf"].Columns.Count; j++)
{
cboField.Items.Add(dgvRecord.Columns[j].HeaderText);
if (dgvRecord.Columns[j].HeaderText == "飞")
{
isL = true;
isY = false;
}
if (dgvRecord.Columns[j].HeaderText == "飞1")
{
isY = true;
isL = false;
}
}
btnCountBase.Enabled = true;
btnCountPhone.Enabled = true;
btnViewt.Enabled = true;
btnViewOutput.Enabled = true;
//btnViewTime.Enabled = true;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
else
{
return;
}
}
//点击GRIDVIEW后查询
private void dgvCountPhone_CellClick(object sender, DataGridViewCellEventArgs e)
{
strFind = Convert.ToString(dgvCountPhone[0, dgvCountPhone.CurrentCell.RowIndex].Value).Trim();
if (isBase && isL)//查看信息
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + RecordFile + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
try
{
string strPhone = "select * from [" + tableNamesArray[0] + "] where
cstr(字段)='" + strFind + "'";
OleDbDataAdapter cmdCountPhone = new OleDbDataAdapter(strPhone, strConn);
DataSet dsPhone = new DataSet();
cmdCountPhone.Fill(dsPhone);
dgvRecord.DataSource = dsPhone.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}