unit loaddata;// -------------------------------------// Load Textfile into table// -------------------------------------interfaceusesWinapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.CheckLst,SynRegExpr, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ToolWin, Vcl.ExtDlgs, System.Math, System.IOUtils, extra_controls,dbconnection, dbstructures, gnugettext;typeTloaddataform = class(TExtForm)btnImport: TButton;btnCancel: TButton;lblDatabase: TLabel;comboDatabase: TComboBox;lblTable: TLabel;comboTable: TComboBox;lblColumns: TLabel;chklistColumns: TCheckListBox;ToolBarColMove: TToolBar;btnColUp: TToolButton;btnColDown: TToolButton;grpFilename: TGroupBox;editFilename: TButtonedEdit;grpChars: TGroupBox;lblFieldTerminater: TLabel;lblFieldEncloser: TLabel;lblFieldEscaper: TLabel;editFieldEscaper: TEdit;editFieldEncloser: TEdit;editFieldTerminator: TEdit;chkFieldsEnclosedOptionally: TCheckBox;grpOptions: TGroupBox;lblIgnoreLinesCount: TLabel;updownIgnoreLines: TUpDown;editIgnoreLines: TEdit;editLineTerminator: TEdit;lblLineTerminator: TLabel;lblIgnoreLines: TLabel;lblFilename: TLabel;comboEncoding: TComboBox;lblEncoding: TLabel;grpDuplicates: TRadioGroup;grpParseMethod: TRadioGroup;grpDestination: TGroupBox;chkLowPriority: TCheckBox;chkLocalNumbers: TCheckBox;chkTruncateTable: TCheckBox;btnCheckAll: TToolButton;chkKeepDialogOpen: TCheckBox;const ProgressBarSteps=100;procedure FormCreate(Sender: TObject);procedure editFilenameChange(Sender: TObject);procedure FormShow(Sender: TObject);procedure comboDatabaseChange(Sender: TObject);procedure comboTablePopulate(SelectTableName: String; RefreshDbObjects: Boolean);procedure comboTableChange(Sender: TObject);procedure btnImportClick(Sender: TObject);procedure ServerParse(Sender: TObject);procedure ClientParse(Sender: TObject);procedure btnOpenFileClick(Sender: TObject);procedure btnColMoveClick(Sender: TObject);procedure grpParseMethodClick(Sender: TObject);procedure FormClose(Sender: TObject; var Action: TCloseAction);procedure chklistColumnsClick(Sender: TObject);procedure btnCheckAllClick(Sender: TObject);procedure FormResize(Sender: TObject);private{ Private declarations }FFileEncoding: TEncoding;FTerm, FEncl, FEscp, FLineTerm: String;FRowCount, FColumnCount: Integer;FColumns: TTableColumnList;FConnection: TDBConnection;public{ Public declarations }property FileEncoding: TEncoding read FFileEncoding;end;implementationuses Main, apphelpers, csv_detector;{$R *.DFM}procedure Tloaddataform.FormCreate(Sender: TObject);beginHasSizeGrip := True;// Restore settingseditFilename.Text := AppSettings.ReadString(asCSVImportFilename);editFieldTerminator.Text := AppSettings.ReadString(asCSVImportSeparator);editFieldEncloser.Text := AppSettings.ReadString(asCSVImportEncloser);editLineTerminator.Text := AppSettings.ReadString(asCSVImportTerminator);chkFieldsEnclosedOptionally.Checked := AppSettings.ReadBool(asCSVImportFieldsEnclosedOptionally);editFieldEscaper.Text := AppSettings.ReadString(asCSVImportFieldEscaper);updownIgnoreLines.Position := AppSettings.ReadInt(asCSVImportIgnoreLines);chkLowPriority.Checked := AppSettings.ReadBool(asCSVImportLowPriority);chkLocalNumbers.Checked := AppSettings.ReadBool(asCSVImportLocalNumbers);chkKeepDialogOpen.Checked := AppSettings.ReadBool(asCSVKeepDialogOpen);// Uncheck critical "Truncate table" checkbox, to avoid accidental data removalchkTruncateTable.Checked := False;grpDuplicates.ItemIndex := AppSettings.ReadInt(asCSVImportDuplicateHandling);grpParseMethod.ItemIndex := AppSettings.ReadInt(asCSVImportParseMethod);end;procedure Tloaddataform.FormResize(Sender: TObject);varHalfWidth, RightBoxX: Integer;begin// Rethink width of side-by-side group boxesHalfWidth := (ClientWidth - 3 * grpFilename.Left) div 2;RightBoxX := HalfWidth + 2 * grpFilename.Left;grpOptions.Width := HalfWidth;grpDuplicates.Width := HalfWidth;grpParseMethod.Width := HalfWidth;grpChars.Width := HalfWidth;grpDestination.Width := HalfWidth;// Move right boxes to the right positiongrpChars.Left := RightBoxX;grpDestination.Left := RightBoxX;end;procedure Tloaddataform.FormShow(Sender: TObject);beginWidth := AppSettings.ReadIntDpiAware(asCSVImportWindowWidth, Self);Height := AppSettings.ReadIntDpiAware(asCSVImportWindowHeight, Self);FConnection := MainForm.ActiveConnection;// Disable features supported in MySQL only, if active connection is not MySQLif not FConnection.Parameters.IsAnyMySQL then begingrpParseMethod.ItemIndex := 1;grpDuplicates.ItemIndex := 0;end;grpParseMethod.Controls[0].Enabled := FConnection.Parameters.IsAnyMySQL;grpDuplicates.Controls[1].Enabled := FConnection.Parameters.IsAnyMySQL;grpDuplicates.Controls[2].Enabled := FConnection.Parameters.IsAnyMySQL;chkLowPriority.Enabled := FConnection.Parameters.IsAnyMySQL;// Read databases and tables from active connectioncomboDatabase.Items.Clear;comboDatabase.Items.Assign(FConnection.AllDatabases);comboDatabase.ItemIndex := comboDatabase.Items.IndexOf(Mainform.ActiveDatabase);if comboDatabase.ItemIndex = -1 thencomboDatabase.ItemIndex := 0;comboDatabaseChange(Sender);editFilename.SetFocus;end;procedure Tloaddataform.FormClose(Sender: TObject; var Action: TCloseAction);begin// Save settingsAppSettings.WriteIntDpiAware(asCSVImportWindowWidth, Self, Width);AppSettings.WriteIntDpiAware(asCSVImportWindowHeight, Self, Height);AppSettings.WriteString(asCSVImportFilename, editFilename.Text);AppSettings.WriteString(asCSVImportSeparator, editFieldTerminator.Text);AppSettings.WriteString(asCSVImportEncloser, editFieldEncloser.Text);AppSettings.WriteString(asCSVImportTerminator, editLineTerminator.Text);AppSettings.WriteBool(asCSVImportFieldsEnclosedOptionally, chkFieldsEnclosedOptionally.Checked);AppSettings.WriteString(asCSVImportFieldEscaper, editFieldEscaper.Text);AppSettings.WriteInt(asCSVImportIgnoreLines, updownIgnoreLines.Position);AppSettings.WriteBool(asCSVImportLowPriority, chkLowPriority.Checked);AppSettings.WriteBool(asCSVImportLocalNumbers, chkLocalNumbers.Checked);AppSettings.WriteBool(asCSVKeepDialogOpen, chkKeepDialogOpen.Checked);AppSettings.WriteInt(asCSVImportDuplicateHandling, grpDuplicates.ItemIndex);AppSettings.WriteInt(asCSVImportParseMethod, grpParseMethod.ItemIndex);end;procedure Tloaddataform.grpParseMethodClick(Sender: TObject);varServerWillParse: Boolean;FileCharset: String;v, i: Integer;beginServerWillParse := grpParseMethod.ItemIndex = 0;comboEncoding.Enabled := ServerWillParse;editFieldEscaper.Enabled := ServerWillParse;chkFieldsEnclosedOptionally.Enabled := ServerWillParse;comboEncoding.Clear;if comboEncoding.Enabled then begin// Populate charset combov := FConnection.ServerVersionInt;if ((v >= 50038) and (v < 50100)) or (v >= 50117) then beginFileCharset := MainForm.GetCharsetByEncoding(FFileEncoding);if FileCharset.IsEmpty thenFileCharset := 'utf8';comboEncoding.Items := FConnection.CharsetList;// Preselect file encoding, or utf8 as a fallbackfor i:=0 to comboEncoding.Items.Count-1 do beginif ExecRegExpr('^'+QuoteRegExprMetaChars(FileCharset)+'\b', comboEncoding.Items[i]) then begincomboEncoding.ItemIndex := i;Break;end;end;end else begincomboEncoding.Items.Add(_(SUnsupported));comboEncoding.ItemIndex := 0;end;end else begincomboEncoding.Items.Add(Mainform.GetEncodingName(FFileEncoding));comboEncoding.ItemIndex := 0;end;end;procedure Tloaddataform.comboDatabaseChange(Sender: TObject);begincomboTablePopulate('', False);grpParseMethod.OnClick(Sender);comboTableChange(Sender);end;procedure Tloaddataform.comboTablePopulate(SelectTableName: String; RefreshDbObjects: Boolean);varcount, i: Integer;DBObjects: TDBObjectList;seldb, seltable: String;begin// read tables from dbcomboTable.Items.Clear;seldb := Mainform.ActiveDatabase;seltable := Mainform.ActiveDbObj.Name;DBObjects := FConnection.GetDBObjects(comboDatabase.Text, RefreshDbObjects);for i:=0 to DBObjects.Count-1 do beginif DBObjects[i].NodeType in [lntTable, lntView] thencomboTable.Items.Add(DBObjects[i].Name);count := comboTable.Items.Count-1;if SelectTableName.IsEmpty and (comboDatabase.Text = seldb) and (comboTable.Items[count] = seltable) thencomboTable.ItemIndex := countelse if (not SelectTableName.IsEmpty) and (SelectTableName = comboTable.Items[count]) thencomboTable.ItemIndex := count;end;if (comboTable.ItemIndex = -1) and (comboTable.Items.Count >= 1) thencomboTable.ItemIndex := 0; // First real tablecomboTable.Items.Add('<'+_('New table')+'>');end;procedure Tloaddataform.comboTableChange(Sender: TObject);varCol: TTableColumn;DBObjects: TDBObjectList;Obj: TDBObject;begin// fill columns, or show csv detector:chklistColumns.Items.Clear;if comboTable.ItemIndex = comboTable.Items.Count-1 then beginfrmCsvDetector := TfrmCsvDetector.Create(Self);case frmCsvDetector.ShowModal ofmrOk: begin// table got created and combo is refreshedend;else begincomboTable.ItemIndex := 0;end;end;frmCsvDetector.Free;frmCsvDetector := nil; // check for Assigned() must be false in SetupSynEditorsend;if (comboDatabase.Text <> '') and (comboTable.Text <> '') then beginif not Assigned(FColumns) thenFColumns := TTableColumnList.Create;DBObjects := FConnection.GetDBObjects(comboDatabase.Text);for Obj in DBObjects do beginif (Obj.Database=comboDatabase.Text) and (Obj.Name=comboTable.Text) then begincase Obj.NodeType oflntTable, lntView: FColumns := Obj.TableColumns;end;end;end;for Col in FColumns dochklistColumns.Items.Add(Col.Name);end;// select all:chklistColumns.CheckAll(cbChecked);chklistColumns.OnClick(Sender);// Ensure valid state of Import-ButtoneditFilenameChange(Sender);end;procedure Tloaddataform.btnImportClick(Sender: TObject);varStartTickCount: Cardinal;i: Integer;beginScreen.Cursor := crHourglass;StartTickCount := GetTickCount;MainForm.EnableProgress(ProgressBarSteps);// Truncate table before importingif chkTruncateTable.Checked then tryFConnection.Query('TRUNCATE TABLE ' + FConnection.QuotedDbAndTableName(comboDatabase.Text, comboTable.Text));FConnection.ShowWarnings;excepttryFConnection.Query('DELETE FROM ' + FConnection.QuotedDbAndTableName(comboDatabase.Text, comboTable.Text));FConnection.ShowWarnings;excepton E:EDbError doErrorDialog(_('Cannot truncate table'), E.Message);end;end;FColumnCount := 0;for i:=0 to chkListColumns.Items.Count-1 do beginif chkListColumns.Checked[i] thenInc(FColumnCount);end;FTerm := FConnection.UnescapeString(editFieldTerminator.Text);FEncl := FConnection.UnescapeString(editFieldEncloser.Text);FLineTerm := FConnection.UnescapeString(editLineTerminator.Text);FEscp := FConnection.UnescapeString(editFieldEscaper.Text);if chkKeepDialogOpen.Checked thenModalResult := mrNone;trycase grpParseMethod.ItemIndex of0: ServerParse(Sender);1: ClientParse(Sender);end;MainForm.LogSQL(FormatNumber(FRowCount)+' rows imported in '+FormatNumber((GetTickcount-StartTickCount)/1000, 3)+' seconds.');// Hint user if zero rows were detected in fileif FRowCount = 0 then beginErrorDialog(_('No rows were imported'),_('This can have several causes:')+CRLF+_(' - File is empty')+CRLF+_(' - Wrong file encoding was selected or detected')+CRLF+_(' - Field and/or line terminator do not fit to the file contents'));ModalResult := mrNone;end;excepton E:EDbError do beginModalResult := mrNone;MainForm.SetProgressState(pbsError);ErrorDialog(E.Message);end;on E:EStreamError do begin// all file stream errors, eg. EFOpenError and EReadError// http://docwiki.embarcadero.com/Libraries/Sydney/en/System.Classes.EStreamErrorModalResult := mrNone;MainForm.SetProgressState(pbsError);ErrorDialog(E.Message + sLineBreak + sLineBreak + editFilename.Text);end;end;if ModalResult = mrNone thenbtnCancel.Caption := _('Close');Mainform.ShowStatusMsg;MainForm.DisableProgress;Screen.Cursor := crDefault;end;procedure Tloaddataform.ServerParse(Sender: TObject);varSQL, SetColVars, SelectedCharset: String;i: Integer;Filename: String;beginSQL := 'LOAD DATA ';if chkLowPriority.Checked and chkLowPriority.Enabled thenSQL := SQL + 'LOW_PRIORITY ';// Issue #1387: Use 8.3 filename, to prevent "file not found" error from MySQL library// Todo: test on WineFilename := ExtractShortPathName(editFilename.Text);if not Filename.IsEmpty thenMainForm.LogSQL('Converting filename to 8.3 format: '+editFilename.Text+' => '+Filename, lcInfo)elseFilename := editFilename.Text;SQL := SQL + 'LOCAL INFILE ' + FConnection.EscapeString(Filename) + ' ';case grpDuplicates.ItemIndex of1: SQL := SQL + 'IGNORE ';2: SQL := SQL + 'REPLACE ';end;SQL := SQL + 'INTO TABLE ' + FConnection.QuotedDbAndTableName(comboDatabase.Text, comboTable.Text) + ' ';SelectedCharset := RegExprGetMatch('^(\w+)\b', comboEncoding.Text, 1);if not SelectedCharset.IsEmpty then beginSQL := SQL + 'CHARACTER SET '+SelectedCharset+' ';end;// Fields:if (FTerm <> '') or (FEncl <> '') or (FEscp <> '') thenSQL := SQL + 'FIELDS ';if editFieldTerminator.Text <> '' thenSQL := SQL + 'TERMINATED BY ' + FConnection.EscapeString(FTerm) + ' ';if FEncl <> '' then beginif chkFieldsEnclosedOptionally.Checked thenSQL := SQL + 'OPTIONALLY ';SQL := SQL + 'ENCLOSED BY ' + FConnection.EscapeString(FEncl) + ' ';end;if FEscp <> '' thenSQL := SQL + 'ESCAPED BY ' + FConnection.EscapeString(FEscp) + ' ';// Lines:if FLineTerm <> '' thenSQL := SQL + 'LINES TERMINATED BY ' + FConnection.EscapeString(FLineTerm) + ' ';if updownIgnoreLines.Position > 0 thenSQL := SQL + 'IGNORE ' + inttostr(updownIgnoreLines.Position) + ' LINES ';// Column listingSQL := SQL + '(';SetColVars := '';for i:=0 to chklistColumns.Items.Count-1 do beginif chklistColumns.Checked[i] then beginif chkLocalNumbers.Checked and (FColumns[i].DataType.Category in [dtcInteger, dtcReal]) then beginSQL := SQL + '@ColVar' + IntToStr(i) + ', ';SetColVars := SetColVars + FConnection.QuoteIdent(chklistColumns.Items[i]) +' = REPLACE(REPLACE(@ColVar' + IntToStr(i) + ', '+FConnection.EscapeString(FormatSettings.ThousandSeparator)+', ''''), '+FConnection.EscapeString(FormatSettings.DecimalSeparator)+', ''.''), ';end elseSQL := SQL + FConnection.QuoteIdent(chklistColumns.Items[i]) + ', ';end;end;SetLength(SQL, Length(SQL)-2);SQL := SQL + ')';if SetColVars <> '' then beginSetLength(SetColVars, Length(SetColVars)-2);SQL := SQL + ' SET ' + SetColVars;end;FConnection.Query(SQL);FRowCount := Max(FConnection.RowsAffected, 0);FConnection.ShowWarnings;end;procedure Tloaddataform.ClientParse(Sender: TObject);varP, ContentLen, ProgressCharsPerStep, ProgressChars: Integer;IgnoreLines, ValueCount, PacketSize: Integer;LineNum: Int64;RowCountInChunk: Int64;EnclLen, TermLen, LineTermLen: Integer;Contents: String;EnclTest, TermTest, LineTermTest: String;Value, SQL: String;IsEncl, IsTerm, IsLineTerm, IsEof: Boolean;InEncl: Boolean;OutStream: TMemoryStream;procedure NextChar;beginInc(P);Inc(ProgressChars);if ProgressChars >= ProgressCharsPerStep then beginMainform.ProgressStep;Mainform.ShowStatusMsg(f_('Importing textfile, row %s, %d%%', [FormatNumber(FRowCount-IgnoreLines), Mainform.ProgressBarStatus.Position]));ProgressChars := 0;end;end;function TestLeftChars(var Portion: String; CompareTo: String; Len: Integer): Boolean;var i: Integer;beginif Len > 0 then beginfor i:=1 to Len-1 doPortion[i] := Portion[i+1];Portion[Len] := Contents[P];Result := Portion = CompareTo;end elseResult := False;end;procedure AddValue;vari: Integer;LowPrio: String;ColumnIndex: Integer;ValuesCounted: Integer;beginInc(ValueCount);if ValueCount <= FColumnCount then beginif Copy(Value, 1, EnclLen) = FEncl then beginDelete(Value, 1, EnclLen);Delete(Value, Length(Value)-EnclLen+1, EnclLen);end;if SQL = '' then beginLowPrio := '';if chkLowPriority.Checked and chkLowPriority.Enabled thenLowPrio := 'LOW_PRIORITY ';case grpDuplicates.ItemIndex of0: SQL := 'INSERT '+LowPrio;1: SQL := 'INSERT '+LowPrio+'IGNORE ';2: SQL := 'REPLACE '+LowPrio;end;SQL := SQL + 'INTO '+FConnection.QuotedDbAndTableName(comboDatabase.Text, comboTable.Text)+' (';for i:=0 to chkListColumns.Items.Count-1 do beginif chkListColumns.Checked[i] thenSQL := SQL + FConnection.QuoteIdent(chkListColumns.Items[i]) + ', ';end;SetLength(SQL, Length(SQL)-2);SQL := SQL + ') VALUES (';end;// Bugfix for #327: Determine column to retrieve the type from by counting the number of columns before the current one INCLUDING the omitted onesColumnIndex := 0;ValuesCounted := 0;for i:=0 to chkListColumns.Items.Count-1 dobeginif chkListColumns.Checked[i] then // column was already countedInc(ValuesCounted); // increase number of counted columnsif ValuesCounted = ValueCount then // did we count all included columns up to the current column?Break;Inc(ColumnIndex); // if all columns (until the current column) are checked, ColumnIndex is ValueCount-1, like before this patchend;if Value <> 'NULL' then beginif chkLocalNumbers.Checked and (FColumns[ColumnIndex].DataType.Category in [dtcInteger, dtcReal]) thenValue := UnformatNumber(Value)elseValue := FConnection.EscapeString(Value, FColumns[ColumnIndex].DataType);end;SQL := SQL + Value + ', ';end;Value := '';end;procedure AddRow;varSA: AnsiString;ChunkSize: Int64;i: Integer;beginif SQL = '' thenExit;Inc(LineNum);for i:=ValueCount to FColumnCount do beginValue := 'NULL';AddValue;end;ValueCount := 0;if LineNum > IgnoreLines then beginDelete(SQL, Length(SQL)-1, 2);StreamWrite(OutStream, SQL + ')');SQL := '';Inc(RowCountInChunk);if (OutStream.Size < PacketSize) and (P < ContentLen) and (RowCountInChunk < FConnection.MaxRowsPerInsert) then beginSQL := SQL + ', (';end else beginOutStream.Position := 0;ChunkSize := OutStream.Size;SetLength(SA, ChunkSize div SizeOf(AnsiChar));OutStream.Read(PAnsiChar(SA)^, ChunkSize);OutStream.Size := 0;FConnection.Query(UTF8ToString(SA), False, lcScript);Inc(FRowCount, Max(FConnection.RowsAffected, 0));FConnection.ShowWarnings;SQL := '';RowCountInChunk := 0;end;end elseSQL := '';end;beginTermLen := Length(FTerm);EnclLen := Length(FEncl);LineTermLen := Length(FLineTerm);SetLength(TermTest, TermLen);SetLength(EnclTest, EnclLen);SetLength(LineTermTest, LineTermLen);InEncl := False;SQL := '';Value := '';OutStream := TMemoryStream.Create;// Turns SQL errors into warnings, e.g. when providing an empty string for an integer columnif FConnection.Parameters.IsAnyMySQL then beginFConnection.Query('/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='''' */');end;MainForm.ShowStatusMsg(f_('Reading textfile (%s) ...', [FormatByteNumber(_GetFileSize(editFilename.Text))]));Contents := ReadTextfile(editFilename.Text, FFileEncoding);ContentLen := Length(Contents);MainForm.ShowStatusMsg;P := 0;ProgressCharsPerStep := ContentLen div ProgressBarSteps;ProgressChars := 0;FRowCount := 0;LineNum := 0;RowCountInChunk := 0;IgnoreLines := UpDownIgnoreLines.Position;ValueCount := 0;PacketSize := SIZE_MB div 2;NextChar;// TODO: read chunks!while P <= ContentLen do begin// Check characters left-side from current positionIsEncl := TestLeftChars(EnclTest, FEncl, EnclLen);IsTerm := TestLeftChars(TermTest, FTerm, TermLen);IsLineTerm := TestLeftChars(LineTermTest, FLineTerm, LineTermLen) and (ValueCount >= FColumnCount-1);IsEof := P = ContentLen;Value := Value + Contents[P];if IsEncl thenInEncl := not InEncl;if IsEof or (not InEncl) then beginif IsLineTerm then beginSetLength(Value, Length(Value)-LineTermLen);AddValue;end else if IsEof then beginAddValue;end else if IsTerm then beginSetLength(Value, Length(Value)-TermLen);AddValue;end;end;if IsLineTerm and (not InEncl) thenAddRow;NextChar;end;// Will check if SQL is empty and not run any query in that case:AddRow;Contents := '';FreeAndNil(OutStream);if FConnection.Parameters.IsAnyMySQL then beginFConnection.Query('/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '''') */');end;end;procedure Tloaddataform.btnOpenFileClick(Sender: TObject);varDialog: TExtFileOpenDialog;TestStream: TFileStream;beginAppSettings.ResetPath;Dialog := TExtFileOpenDialog.Create(Self);Dialog.DefaultFolder := ExtractFilePath(editFilename.Text);Dialog.FileName := ExtractFileName(editFilename.Text);Dialog.AddFileType('*.csv', _('CSV files'));Dialog.AddFileType('*.txt', _('Text files'));Dialog.AddFileType('*.*', _('All files'));Dialog.DefaultExtension := 'csv';Dialog.Encodings.Assign(Mainform.FileEncodings);Dialog.EncodingIndex := AppSettings.ReadInt(asFileDialogEncoding, Self.Name);if Dialog.Execute then begineditfilename.Text := Dialog.FileName;FFileEncoding := Mainform.GetEncodingByName(Dialog.Encodings[Dialog.EncodingIndex]);if FFileEncoding = nil then beginMessageDialog(_('Auto detecting the encoding of a file is highly discouraged. You may experience data loss if the detection fails.') +SLineBreak + SLineBreak +_('To avoid this message select the correct encoding before pressing Open.'),mtWarning, [mbOK]);TestStream := TFileStream.Create(Dialog.Filename, fmOpenRead or fmShareDenyNone);FFileEncoding := DetectEncoding(TestStream);TestStream.Free;end;grpParseMethod.OnClick(Sender);AppSettings.WriteInt(asFileDialogEncoding, Dialog.EncodingIndex, Self.Name);end;Dialog.Free;end;procedure Tloaddataform.chklistColumnsClick(Sender: TObject);vari, CheckedNum: Integer;beginbtnColDown.Enabled := (chklistColumns.ItemIndex > -1)and (chklistColumns.ItemIndex < chklistColumns.Count-1);btnColUp.Enabled := (chklistColumns.ItemIndex > -1)and (chklistColumns.ItemIndex > 0);// Toggle icon when none is selectedCheckedNum := 0;for i:=0 to chklistColumns.Items.Count-1 do beginif chklistColumns.Checked[i] thenInc(CheckedNum);end;if CheckedNum < chklistColumns.Items.Count thenbtnCheckAll.ImageIndex := 127elsebtnCheckAll.ImageIndex := 128;end;procedure Tloaddataform.btnCheckAllClick(Sender: TObject);vari, CheckedNum: Integer;beginCheckedNum := 0;for i:=0 to chklistColumns.Items.Count-1 do beginif chklistColumns.Checked[i] thenInc(CheckedNum);end;if CheckedNum < chklistColumns.Items.Count thenchklistColumns.CheckAll(cbChecked)elsechklistColumns.CheckAll(cbUnchecked);chklistColumns.OnClick(Sender);end;procedure Tloaddataform.btnColMoveClick(Sender: TObject);varCheckedSelected, CheckedTarget: Boolean;TargetIndex: Integer;begin// Move column name and its checkstate up or downif Sender = btnColUp thenTargetIndex := chklistColumns.ItemIndex-1elseTargetIndex := chklistColumns.ItemIndex+1;if (TargetIndex > -1) and (TargetIndex < chklistColumns.Count) then beginCheckedSelected := chklistColumns.Checked[chklistColumns.ItemIndex];CheckedTarget := chklistColumns.Checked[TargetIndex];chklistColumns.Items.Exchange(chklistColumns.ItemIndex, TargetIndex);chklistColumns.Checked[chklistColumns.ItemIndex] := CheckedTarget;chklistColumns.Checked[TargetIndex] := CheckedSelected;chklistColumns.ItemIndex := TargetIndex;end;chklistColumns.OnClick(Sender);end;{** Make "OK"-button only clickable if- filename is not empty- table is selected- columnnames could be fetched normally- filename exists}procedure Tloaddataform.editFilenameChange(Sender: TObject);beginbtnImport.Enabled := (editFilename.Text <> '')and (chklistColumns.Items.Count > 0)and (FileExists(editFilename.Text));end;end.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。