How to make Pandas Excel writer append to an existing sheet in a workbook instead of creating a new worksheet? - pandas

I have a excel workbook with two sheets ('variable','fixed'). In parallel, I have a data frame (pandas) with some data. I want to append the data in the data frame to the sheet ('variable') below the existing data in that sheet. But, the following code creates a new sheet called 'variable1' and dumps the data instead of appending to sheet 'variable'.
path = "data.xlsx"
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine='openpyxl', mode='a')
writer.book = book
df3.to_excel(writer, sheet_name="variable",startrow=9,
index=False,header=False)
writer.save()
writer.close()
I have tried the above code. df3 is my pandas dataframe. I want my data to be pasted from row 9 as the existing data is until row 8 in sheet 'variable'. The code creates a new sheet ('variable1') and dumps data from row 9. I want it to paste the info in sheet ('variable') and not create a new one.
Can someone help me understand this dynamic?

To append an excel document use:
# open the workbook
wb = openpyxl.load_workbook('file_name.xlsx')
# assign a var to worksheet
ws = wb['sheet_name']
Then you can do things like:
# write to cell
wb['sheet_name'].cell(row=4, column=1).value = string_to_enter_to_cell
# format cells
for row in ws['A4:L4']:
for cell in row:
cell.value = None
cell.border = no_border

Related

VBA Excel - Generate New Workbook with macros from Old Workbook

I currently have a workbook which contains a bunch of data on 2 of the sheets, which i use to construct a chart. Here's what it looks like:
So, In CRC I have a bunch of macros which pull through data from the Generator and MPNT and Construct the Chart in the CRC when a button on the MPNT is pressed.
MY ISSUE
For some reason, when I copy the CRC sheet out into a new worksheet using the function below, and then I use one of the buttons on the worksheet to hide/unhide data columns on the chart, it opens up the original file and uses the macros in that to run these buttons?
'''Extract Worksheet Button Function
Dim OriginalWB As Workbook, NewCRCWB As Workbook
Set OriginalWB = ThisWorkbook
Set NewCRCWB = Workbooks.Add
OriginalWB.Sheets("Generator").Copy Before:=NewCRCWB.Sheets("Sheet1")
OriginalWB.Sheets("Module Part Number Tracker").Copy Before:=NewCRCWB.Sheets("Generator")
OriginalWB.Sheets("CRC").Copy Before:=NewCRCWB.Sheets("Module Part Number Tracker")
Application.DisplayAlerts = False
NewCRCWB.Worksheets("Generator").Visible = False
NewCRCWB.Worksheets("Module Part Number Tracker").Visible = False
NewCRCWB.Worksheets("Sheet1").Delete
NewCRCWB.Activate
Application.DisplayAlerts = True
End Sub
MY AIM
To get around this I need to develop a function which will create a new workbook, and do all of the generation straight into that workbook and transfer the macros into there, however I'm not sure how to do this hence
MY QUESTION
How do I:
Open a New Workbook
Run the macros from CRC in current
workbook onto a CRC sheet on the newly opened workbook
In the process ensure that all the macros are copied through to the CRC
sheet in the New Workbook
Thanks!!

Unable to create a logic to convert the values in Excel to CSV the right way with VBA

I made the code to convert the values to the csv file but the problem is
that I'm not sure if this is the right way because this is the first time I even touched VBA macro! As seen in the image I provided, there is a button "Convert to CSV", when I tap it, the macro will call ExportWorksheetAndSaveAsCSV method and will convert the entire sheets contents into csv. However, it looks like it converts the entire sheet it'self.
What I want to do is the following steps .
1.Pass in the Sheet name as a parameter like ExportWorksheetAndSaveAsCSV("Sheet2"), so that it can be used as a file name. But I'm not sure how I can pass a parameter in function from the Buttton.
2.Convert the values in the columns E to I to CSV. If possible want to have the tites of the data show in the first row of the csv file.
I attached the image and the code so you can see. Some tips or examples will be really helpful! I would love to hear from you.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim book As String
Dim fileName As String
book = "Sheet1"
fileName = "test.csv"
Set shtToExport = ThisWorkbook.Worksheets(book) 'Export to CSV file
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs fileName:="C:\Users\myStuff\Documents\" & fileName, FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub

Setting custom header on each page of an excel sheet using xlsxwriter

Is it possible to set custom header on each page within the same sheet in excel using xlsxwriter?
Here I get two pages, but the same header on each. So this just sets for the entire sheet.
import xlsxwriter
data = ["a", "b", "c"]
wb = xlsxwriter.Workbook('test.xlsx')
ws = wb.add_worksheet()
for index,d in enumerate(data):
ws.write(index,0,d)
ws.print_area(index,0,index,10)
ws.set_header("&C Header %s"%d)
ws.set_h_pagebreaks([index])
ws.set_page_view()
wb.close()

Read values from named ranges with openpyxl

How can I read values from named ranges in Excel with openpyxl?
I've found the sourcecode at http://openpyxl.readthedocs.org/en/latest/_modules/openpyxl/workbook/names/named_range.html but I can't figure out how to use it properly.
wb = openpyxl.load_workbook(excel_file_name)
rng = wb.get_named_range(name_of_range).destinations[0]
sheet = rng[0]
address = rng[1].replace('$','')
val = sheet[address].value

apache poi: change the font of existing entire sheet

I has a existing workbook containing multiple sheets. I have a sheet which contains some bold cells in it. I want to change the font of this entire sheet retaining the boldness of some of the cells. Can you please provide me the code snippet?
You will have to create more than one style for the workbook:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle fontStyleBold = wb.createCellStyle();
XSSFCellStyle fontStyleNormal = wb.createCellStyle();
and assign the cells you want.