public
strCSV : String;
CSVFile, TEXTFile : TextFile;
Openfilename :String;
procedure TfrmConverter.butImportClick(Sender: TObject);
var
openDialog : TOpenDialog; // Open dialog variable
strTmp : string;
begin
openDialog := TOpenDialog.Create(self);
openDialog.InitialDir := GetCurrentDir;
openDialog.Options := [ofFileMustExist]; // Only allow existing files to be selected
openDialog.Filter := 'CSV files|*.csv';
// Display the open file dialog
if openDialog.Execute
then
begin
Openfilename := openDialog.FileName;
openDialog.Free; // Free up the dialog
End
else
begin
ShowMessage('Open file was cancelled');
exit;
end;
Try
AssignFile(CSVFile, Openfilename);
strCSV :=''; //every new import needs to clear strCSV
Reset(CSVFile);
while not Eof(CSVFile) do
begin
ReadLn(CSVFile, strTmp);
strCSV := strCSV + strTmp;
end;
CloseFile(CSVFile);
Except
ShowMessage('File Operation Fails');
End;
procedure TfrmConverter.butSaveClick(Sender: TObject);
var
saveDialog : TSaveDialog; // Save dialog variable
strTmp2 :String;
OpenfileLength, Openfilepointer: integer;
begin
// Create the save dialog object - assign to our save dialog variable
saveDialog := TSaveDialog.Create(self);
saveDialog.Title := 'Save your Text File';
saveDialog.InitialDir := GetCurrentDir;
saveDialog.Filter := 'Text file|*.txt';
saveDialog.DefaultExt := 'txt';
// remove the path of the filename
Repeat
OpenfileLength := length(Openfilename);
Openfilepointer :=Pos('\',Openfilename);
Openfilename := Copy(Openfilename,Openfilepointer+1,OpenfileLength-Openfilepointer);
Until (Openfilepointer=0);
// remove the extension of the filename
strTmp2 := lowercase(Openfilename);
Openfilepointer :=Pos('.csv',strTmp2);
Openfilename := Copy(Openfilename,1,Openfilepointer-1);
saveDialog.FileName := Openfilename;
// Display the open file dialog
if saveDialog.Execute
then
begin
strTmp2 := saveDialog.FileName;
saveDialog.Free; // Free up the dialog
Try
AssignFile(TEXTFile,strTmp2);
Rewrite(TEXTFile );
Writeln(TEXTFile ,strCSV );
closeFile(TEXTFile );
Except
ShowMessage('File Operation Fails');
End;
End
else ShowMessage('Save file was cancelled');
End;作者: admin 時間: 2012-7-9 09:21
{ Create a new stream writer directly. }
Writer := TStreamWriter.Create(strTmp2,false, TEncoding.UTF8);
{ Store the title and then the text. }
//Writer.WriteLine(''); //add 0D 0A after write the data
Writer.Write(strCSV);
{ Close and Free the writer. }
Writer.Free();