需要把从数据库中读出的数据写到excel文件中,每列对应excel文件的一列.现做法是存成txt文件,再用excel打开,但是由数字组成的字符列变成数字类型的列.例如"001"变成"1"(字符串开头的字符"0"被去掉了),请问高手如何解决.

解决方案 »

  1.   

    procedure WriteExcel(ds: TQuery; sName: string);
    var
      ExcelApplication1: TExcelApplication;
      ExcelWorksheet1: TExcelWorksheet;
      ExcelWorkbook1: TExcelWorkbook;
      i, j, n: integer;
      filename: string;
    begin
      filename := concat( sName, '.xls');
      try
        ExcelApplication1 := TExcelApplication.Create(Application);
        ExcelWorksheet1 := TExcelWorksheet.Create(Application);
        ExcelWorkbook1 := TExcelWorkbook.Create(Application);
        ExcelApplication1.Connect;
      except
        Application.Messagebox('Excel 没有安装!', 'Hello', MB_ICONERROR + mb_Ok);
        Abort;
      end;
      try
        ExcelApplication1.Workbooks.Add(EmptyParam, 0);
        ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks[1]);
        ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Worksheets[1] as _worksheet);
        ds.First;
        n:=1;
        for j := 0 to ds.Fields.Count - 1 do
          if frmMain.grdMain.Columns[j].Visible = True then
          begin
            ExcelWorksheet1.Cells.item[1, n] := ds.Fields[j].DisplayLabel;
            ExcelWorksheet1.Cells.item[1, n].font.size := '10';
            n:=n+1;
          end;
        for i := 2 to ds.RecordCount + 1 do
        begin
          n:=1;
          for j := 0 to ds.Fields.Count - 1 do
            if frmMain.grdMain.Columns[j].Visible = True then
            begin
              ExcelWorksheet1.Cells.item[i, n] :=
                  ds.Fields[j].AsString;
              ExcelWorksheet1.Cells.item[i, n].font.size := '10';
              n:=n+1;
            end;
          ds.Next;
          end;
        ExcelWorksheet1.Columns.AutoFit;
        ExcelWorksheet1.SaveAs(filename);
        Application.Messagebox(pchar('数据成功导出' + filename), 'Hello',
          mb_Ok);
      finally
        ExcelApplication1.Disconnect;
        ExcelApplication1.Quit;
        ExcelApplication1.Free;
        ExcelWorksheet1.Free;
        ExcelWorkbook1.Free;
      end;
    end;
    对你可能有帮助,不过整个方法速度一般
      

  2.   

    那是excel的字符类型设置的不对。
      

  3.   

    OleServer, Excel2000
    可能要加这两个单元,记不清楚了