473,326 Members | 2,128 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

How to keep columns header on excel without change after export data to excel file?

1 Bit
I work on sql server 2017 I run script depend on python language v 3.10 .

I need to export data to excel fileStudentExport.xlsx already exist, and keep header without change after export.

header of excel file StudentExport.xlsx before export data to it as below

StudentId,StudentName

after run script query to export data to StudentExport.xlsx and Header changed to

StudentId,Name

my issue is header changed from column name StudentName to Name (exist on sql)

I export data to excel by this line

Expand|Select|Wrap|Line Numbers
  1. InputDataSet.to_excel(FullFilePath,sheet_name=TableName.split(".")[-1],index=False)
I try to change InputDataSet.to_excel it to keep header on excel file StudentExport.xlsx without change as below

Expand|Select|Wrap|Line Numbers
  1. InputDataSet.to_excel(FullFilePath,sheet_name=TableName.split(".")[-1], header=False, startrow= 1,index=False)
but it give me data without header and header row blank

so can any one help me to export data to excel file without change or overwrite header ?

Notes Not practical way to change column name from Name to StudentName on sql server table create view to use it as excel header .

expected result

StudentId StudentName
1 ahmed
script Query I run it as below for lookup

Expand|Select|Wrap|Line Numbers
  1. declare @ExportPath NVARCHAR(MAX)='G:\ImportExportExcel'
  2. declare @FixedPath NVARCHAR(MAX)='G:\ExportFiles\StudentExport.xlsx'
  3. CREATE TABLE #FinalExportList(TableCount INT IDENTITY(1,1),Cols NVARCHAR(MAX),TableName NVARCHAR(200))
  4. insert into #FinalExportList(TableName,Cols)
  5. values
  6. ('dbo.students','TRY_CONVERT(VARCHAR(MAX),StudentId) AS [StudentId], Name')
  7.  
  8. DECLARE
  9. @TableName NVARCHAR(200)
  10. ,@SQL NVARCHAR(MAX) = N''
  11. ,@PythonScript NVARCHAR(MAX) = N''
  12. ,@ExportFilePath NVARCHAR(MAX) = N''
  13.  
  14.  
  15. SELECT @ExportPath = CASE WHEN RIGHT(@ExportPath,1) = '\' THEN @ExportPath ELSE CONCAT(@ExportPath,'\') END
  16.  
  17.  
  18. -- Just for testing purpose top 10 records are selected
  19. SELECT @SQL = CONCAT('SELECT TOP 10 ',Cols,' FROM ',TableName,';')
  20. ,@TableName = TableName
  21. FROM #FinalExportList
  22.  
  23.  
  24. SET @PythonScript = N'import shutil
  25. FullFilePath = ExcelFilePath+"StudentExport.xlsx"
  26. shutil.copy(FixedPath,ExportPath)
  27. InputDataSet.to_excel(FullFilePath,sheet_name=TableName.split(".")[-1],index=False)
  28. 'f
  29.  
  30. exec sp_execute_external_script
  31. @language = N'Python'
  32. ,@script = @PythonScript
  33. ,@input_data_1 = @SQL
  34. ,@params = N'@ExcelFilePath NVARCHAR(MAX), @TableName NVARCHAR(200),@FixedPath NVARCHAR(MAX),@ExportPath NVARCHAR(MAX)'
  35. ,@ExcelFilePath = @ExportPath -- file path where Excel files are placed
  36. ,@TableName = @TableName
  37. ,@FixedPath=@FixedPath
  38. ,@ExportPath=@ExportPath
  39. sql server table
  40.  
  41. CREATE TABLE [dbo].[students](
  42.  [StudentId] [int] NOT NULL,
  43.  [Name] [varchar](50) NULL,
  44.   CONSTRAINT [PK_students] PRIMARY KEY CLUSTERED 
  45.  (
  46.  [StudentId] ASC
  47.  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  48.  ) ON [PRIMARY]
  49.  GO
  50.  INSERT [dbo].[students] ([StudentId], [Name]) VALUES (1, N'ahmed')
May 3 '22 #1
0 9621

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Daniel Chartier | last post by:
Hello, all. I found a bit of code that lets me read an Excel file from and to a specifi range. See the code below. But what if I only want to specify the STARTING position and simply want it...
0
by: Sridhar | last post by:
Hi, I have a export to excel function where it exports the data of a datagrid into the excel sheet. For this, I am using the button and the text on that button reads "Export to Excel". Instead...
0
by: Server Control | last post by:
Hi, I am exporting my datagrid to Excel using the standard Export to Excel Method using : dg.RenderControl(). and Page.Response.AddHeader("Content-Disposition", "attachment;filename=" +...
6
Vasuki Masilamani
by: Vasuki Masilamani | last post by:
Hi, I need a query which would convert Columns into Rows without causing any damages to the original data. I am not supposed to solve this by creating temporary tables and later dropping it. I...
0
by: johnlim20088 | last post by:
Hi, Can someone help me on this? What can I done on code? I able to export csv file in http://mypage.com, but when i change to https://mypage.com, it unable to export, error "cannot display...
3
by: ashwinkpes | last post by:
Hi i am new to ssis and i am trying to transfer data from excel file with multiple workbooks(tables) to oledb destination.......i followed the instructions given in msdn but they r vague and do not...
3
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I have a question for you. I have a .csv file which has many lines of data. Each line has many data fields which are delimited by ",". Now I need to extract part of data from this...
0
by: Ivan Stefanov | last post by:
Hello, I have the following problem: I created a website project and I want in that website to be make a button, which will export some data in an excel file. This is the code that I have: using...
0
by: samchuah911 | last post by:
I using visual basic 2010 and I want to extract the data I had insert in the exe.file to excel without overwrite the data or design of it. Below is the code I use Dim oExcel As Object ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.