代码如下:
const
cSql = 'select * from [%s$]';
var FileName : string;
flag : Boolean;
_TableList,AData: TStringList;
_TableName,str1 : string;
arr1 : array of string;
_Index,k,i : Integer;
begin
dlgOpen1.Create(nil);
//指定默认打开路径
dlgOpen1.InitialDir:='C:\Users\Administrator\桌面';
dlgOpen1.Filter:='Excel文件|*.xls';
flag:=dlgOpen1.Execute;
if not flag then
begin
dlgOpen1.Free;
end;
FileName:=dlgOpen1.FileName;
conn := TADOConnection.Create(nil);
conn.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+FileName+';Extended Properties=excel 8.0;Persist Security Info=False';
conn.LoginPrompt := False;
conn.Connected := True;
_TableList := TStringList.Create;
conn.GetTableNames(_TableList);
//SetLength(arr1,9);
AData := TStringList.Create;
if _TableList.Count > 0 then
begin
_TableName := StringReplace(_TableList.Strings[0], '$', '', [rfReplaceAll]); //+'$'
qry1.Connection := conn;
qry1.Close;
qry1.sql.Text := Format(cSql,[_TableName]);
qry1.Open;
DSXLS.DataSet := qry1;
//GridXLS.Datasource :=DSXLS;
end;
k := 0;i := 0;
if qry1.RecordCount>0 then
begin
while not qry1.Eof do
begin
AData.Add(qry1.Fields[0].AsString);
str1 := AData.Strings[0];
AData.Add(qry1.Fields[1].AsString);
AData.Add(qry1.Fields[2].AsString);
AData.Add(qry1.Fields[3].AsString);
AData.Add(qry1.Fields[4].AsString);
AData.Add(qry1.Fields[5].AsString);
AData.Add(qry1.Fields[6].AsString);
AData.Add(qry1.Fields[7].AsString);
AData.Add(qry1.Fields[8].AsString);
// arr1[0] := qry1.Fields[0].Value;
// arr1[1] := qry1.Fields[1].Value;
// arr1[2] := qry1.Fields[2].Value;
// arr1[3] := qry1.Fields[3].Value;
// arr1[4] := qry1.Fields[4].Value;
// arr1[5] := qry1.Fields[5].Value;
// arr1[6] := qry1.Fields[6].Value;
// arr1[7] := qry1.Fields[7].Value;
// arr1[8] := qry1.Fields[8].Value;
if (AData.Strings[0]<>'合计1')and(AData.Strings[0]<>'总计2')and(AData.Strings[0]<>'总计3') then
begin
_Index := cxgrdtblvw1.DataController.AppendRecord;
cxgrdtblvw1.DataController.Values[_Index,0] := AData.Strings[0];
cxgrdtblvw1.DataController.Values[_Index,1] := AData.Strings[1];
cxgrdtblvw1.DataController.Values[_Index,2] := AData.Strings[2];
cxgrdtblvw1.DataController.Values[_Index,3] := AData.Strings[3];
cxgrdtblvw1.DataController.Values[_Index,4] := AData.Strings[4];
cxgrdtblvw1.DataController.Values[_Index,5] := AData.Strings[5];
cxgrdtblvw1.DataController.Values[_Index,6] := AData.Strings[6];
cxgrdtblvw1.DataController.Values[_Index,7] := AData.Strings[7];
cxgrdtblvw1.DataController.Values[_Index,8] := AData.Strings[8];
AData.Clear;
k := k+1;
Application.ProcessMessages;
cxgrdtblvw1.DataController.Post;
end
else
begin
if Trim(str1)='合计1' then
ShowMessage('1');
end;
qry1.Next;
end;
cxgrdtblvw1.DataController.Post;
showMessage(inttostr(k));
end;
end;
这是一段通过ADO加载Execl在cxGrid显示的代码。其中第一行是‘合计1’‘总计2’‘总计3’的数据不导入,而我这段代码的问题在于我依旧在cxGrid中看到导出结果有‘合计1’‘总计2’‘总计3’的数据,打了断点也看到值一样没有差错。
最后想到了原来是StringList中的String是有空格的。所以debug的时候’合计1’<>’合计1’的结果是true,实际上是’合计1 ‘<>’合计1’.