void __fastcall TIWForm1::IWButton1Click(TObject *Sender)
{
FileOpenDialog1->Title="请选择导入的文件!";
//设置对话框
//OpenDialog1->InitialDir=Path; //"f:/";
//初始化路径
//FileOpenDialog1->Filter="Text Files(*.xls)|*.xls|ALL Files(*.*)|*.*";
//设置文件过滤
//FileOpenDialog1->DefaultExt="XLS";
//设置缺省扩展名
if(FileOpenDialog1->Execute())
{
//ADOQuery1->ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};DBQ=.\\wsj";
//ADOQuery1->SQL->Text = "Select * from [Sheet1$]";
//
AnsiString SQLstr;
SQLstr="Select * from [Sheet1$]";
ShowTable(FileOpenDialog1->FileName.c_str(), SQLstr,IWGrid1);
IWGrid1->Perform(WM_VSCROLL,SB_BOTTOM,0);
//生成日志
//Form1->AdvMemo1->Lines->Add(AnsiString(Now().TimeString() )+"@打开EXCEL文档@"+Form1->OpenDialog1->FileName);
}
}
//---------------------------------------------------------------------------
void __fastcall TIWForm1::ShowTable(AnsiString strFile, AnsiString SQLstr,TIWGrid *SXgrid)
{
// ADO连接
TADOConnection *con = new TADOConnection(NULL);
TADOQuery *aq = new TADOQuery(NULL);
aq->Connection = con;
// 连接该MDB数据库
AnsiString s;
//con->ConnectionString ="Driver={Microsoft Excel Driver (*.xls)};DBQ="+strFile;
con->ConnectionString ="Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Data Source="+strFile+
";Extended Properties='Excel 12.0 XML;HDR=YES'";
//FDConnection1->ConnectionString= "DriverID=ODBC;ODBCAdvanced=\"ReadOnly=True;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ="+strFile;
try
{
con->Connected = true;
}
catch (...)
{
delete aq;
delete con;
//MessageBox(0,L"连接数据库失败",L"失败",MB_OK);
return;
}
//----------------------------
//-----------------------------
// 如果连接成功,就通过ADOQuery读取字段
aq->SQL->Text =SQLstr;
try
{
aq->Open();
}
catch(...)
{
delete aq;
delete con;
//MessageBox(0,L"打开表失败",L"失败",MB_OK);
return;
}
//----------------------------
//-----------------------------
//彩果属性装入
SXgrid->ColumnCount =aq->FieldCount;
SXgrid->RowCount =aq->RecordCount+1;
//读取EXCEL表头
for(int i=0;i<aq->FieldCount;i++)
{
SXgrid->Cell[0][i]->Text =aq->Fields->Fields[i]->FieldName;
//SXgrid->AutoSizeCol(i);
//if(aq->Fields->Fields[i]->AsString.Length()*15<20)
//SXgrid->Cell[i] =40;
//else
//SXgrid->ColWidths[i]=aq->Fields->Fields[i]->AsString.Length()*12;
}
//----------------------------
//-----------------------------
//读取EXCEL表内容
int k=0;
aq->First();
while(!aq->Eof)
{
for(int i=0;i<aq->FieldCount;i++)
{
SXgrid->Cell[k+1][i]->Text=aq->Fields->Fields[i]->AsString;
}
k++;
aq->Next();
//----------------------------
//-----------------------------
}
delete aq;
aq=NULL;
delete con;
con=NULL;
//----------------------------------
}