通过OLE将ListView数据导出到Excel

procedure TfrmMain.ExportListToExcel(showWhenFinished:Boolean = False); var fileName, strItem: string; excelObj: Variant; workbook, worksheet: OleVariant; i, j: integer; begin fileName := 'C:/MyExcel.xls'; try excelObj := CreateOleObject('Excel.Application'); excelObj.Application.Workbooks.Add; excelObj.Caption := '将列表导出到Excel表格中'; workbook := excelObj.Application.workbooks[1]; worksheet := workbook.WorkSheets.Item[1]; for i := 0 to lvwRvuInfo.Columns.Count-1 do begin worksheet.Cells[1,i+1] := lvwRvuInfo.Columns[i].Caption; end; for i := 0 to lvwRvuInfo.Items.Count-1 do begin for j := 0 to lvwRvuInfo.Columns.Count - 1 do begin if (j=0) then strItem := lvwRvuInfo.Items[i].Caption else strItem := lvwRvuInfo.Items[i].SubItems[j-1]; worksheet.Cells[i+2, j+1] := strItem; end; end; if showWhenFinished then begin excelObj.Application.Visible := true; end else begin excelObj.Application.DisplayAlerts := false; workbook.SaveAs(fileName); stbMain.Caption := '报表已自动保存为:' + fileName; end; excelObj.Application.Quit; except ShowMessage('创建Excel文件失败,请检查您是否安装了Excel!'); end; end;

你可能感兴趣的:(c,ListView,String,Excel,报表)