I need to append data to excel file already exist from table students on SQL Server .
So I need to append data when dbo.fn_FileExists(@FullFilePath)=1
Excel file already Created on D:\ExportExcel\dbo.students.xlsx with student IDs 1 and 2.
student table with old data
studentid Name
1 ahmed
2 eslam
Table structure:
CREATE TABLE [dbo].[students](
[StudentId] [int] NOT NULL,
[Name] varchar NULL,
CONSTRAINT [PK_students] PRIMARY KEY CLUSTERED
(
[StudentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT [dbo].[students] ([StudentId], [Name]) VALUES (3, NâSayedâ)
INSERT [dbo].[students] ([StudentId], [Name]) VALUES (4, NâMichelâ)
Python script used
DECLARE @PythonScript NVARCHAR(MAX) = Nââ
declare @SQL NVARCHAR(MAX) = Nâselect studentid,Name from dbo.students;â
declare @ExportPath varchar(max)=âD:\ExportExcel'
declare @TableName varchar(max)=âdbo.studentsâ
declare @FullFilePath varchar(max) = concat(@ExportPath,@TableName+â.xlsxâ)
âIF File Not Exist
if(dbo.fn_FileExists(@FullFilePath)=0)
BEGIN
âprint âCreate Fileâ
SET @PythonScript = Nâ
FullFilePath = ExcelFilePath+TableName+â.xlsxâ
InputDataSet.to_excel(FullFilePath,sheet_name=TableName.split(â.â)[-1],index=False)â
EXEC sp_execute_external_script
@language = NâPythonâ
,@script = @PythonScript
,@input_data_1 = @SQL
,@params = Nâ@ExcelFilePath NVARCHAR(MAX), @TableName NVARCHAR(200)â
,@ExcelFilePath = @ExportPath â file path where Excel files are placed
,@TableName = @TableName
END
ELSE
BEGIN
âappend data
âHere code i need to write to append data
print âAppend dataâ
END
When use Python script it will not append data to Excel file from table students. Meaning it will not add student IDs 3 and 4 .
So How to append data from table students to excel file using Python script?
Expected result to file after append
after append data to excel
studentid Name
1 ahmed
2 eslam
3 Sayed
4 Michel