How to insert data into excel in Horizontal? - python-3.x

import xlwt
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Sheet1', cell_overwrite_ok=True)
data = (
[(1,),(2,),(3,)],
[('a',),('b',),('c',)],
[('e',),('f',),('g',)],
)
for index, value in enumerate(data):
for r_num, r_value in enumerate(value):
ws.write(r_num, index,r_value[0])
wb.save('test.xls')
My result is as below. But how can I insert mydata into excel in Horizontal?

If I understand you question the right way, you want the numbers to be in the top row. If so, you can just replace ws.write(r_num, index,r_value[0]) with ws.write(index, r_num,r_value[0]).

Related

Case insensitive search of an Excel file using Pandas read_excel

I need to get sheets from an Excel file with a certain name. Unfortunately sometimes the sheet names are not formatted correctly ie "Test Sheet" vs "Test sheet". I need a case insestive way of getting these sheets.
excel_file= pd.ExcelFile("file_name.xlsx")
sheet_needed = pd.read_excel(excel_file, sheet_name="Test Sheet") # <- This needs to be case insensitive
So pandas doesnt seem to have a good way of having a case insensitive search, However you can get the sheetnames as a list and pd.read will accept an index for the sheet name so I came up with this to solve the problem
excel_file= pd.ExcelFile("file_name.xlsx")
sheet_to_find = "Test Sheet"
# Get all the sheetnames as a list
sheet_names = excel_file.sheet_names
# Format the list of sheet names
sheet_names = [name.lower() for name in sheet_names]
# Get the index that matches our sheet to find
index = sheet_names.index(sheet_to_find.lower())
# Feed this index into pandas
sheet_needed = pd.read_excel(excel_file, sheet_name=index)
I don't know how to make that request case insesitive, but you could try to manipulate the file with openpyxl something like this:
import openpyxl
filename = 'file_name.xlsx'
wb = openpyxl.load_workbook(filename)
for ws in wb.worksheets:
ws.title = ws.title.title()
filename = 'new_'+filename
wb.save(filename)
wb.close()
the old title gets replaced with the 'titlelized' name of itself. You could also use the lower() or upper() function of the str object for that.

Python3 - Openpyxl - For loop to search through Column - Gather information Based on position of first cell location

UPDATE!
My goal is to modify an existing Workbook ( example - master_v2.xlsm ) and produce a new workbook (Newclient4) based on the updates made to master_v2.
I'm using a single sheet within master_v2 to collect all the data which will be determining what the new workbook will be.
Currently using multiple if statements to find the value of the cells in this "repository" sheet. Based on specific cells, I'm creating and adding values to copies of an existing sheet called "PANDAS".
My goal right now is to create a dict based on two columns. The loop through
the keys so that every time I get a hit on a cell, I will gather values from specific keys.
That's listed below:
from openpyxl import load_workbook
# Start by opening the spreadsheet and selecting the main sheet
workbook = load_workbook(filename="master_v2.xlsm",read_only=False, keep_vba=True)
DATASOURCE = workbook['repository']
DATASOURCE["A:H"]
cell100 = DATASOURCE["F6"].value
CREATION = cell100
cell101 = DATASOURCE["F135"].value
CREATION2 = cell101
cell107 = DATASOURCE["F780"].value
CREATION7 = cell107
if CREATION.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H4'].value[0:12]+' PANDAS'
if CREATION2.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H133'].value[0:12]+' PANDAS'
if CREATION3.isnumeric():
source = workbook['PANDAS']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H262'].value[0:12]+' PANDAS'
else:
print ("no")
workbook.save(filename="NewClient4.xlsm")
Instead of the many if statements I was hoping to be able to loop through the column as explained above,
once I found my value, gather data and copy it over to a copy of sheet which is then filled out by other cells. Each time the loop comples, I want to do repeat on the next match of the string.. but I'm only this far and it's not quite working.
Anyone have a way to get this working?
( trying to replace the many one to one mappings and if statements )
for i in range(1,3000):
if DATASOURCE.cell(row=i,column=5).value == "Customer:":
source = workbook['Design details']
target = workbook.copy_worksheet(source)
ss_sheet = target
ss_sheet.title = DATASOURCE['H4'].value[0:12]+' Design details'
else:
print ("no")
Thank you guys in advanced

How to cancel auto filter on table with openpyxl

The title said it all :)
But still, I'm using the class Table from openpyxl.worksheet.table to define a table in excel file which I create. My problem is that the table that is created has Filter on the first row that I want to remove (from the script, not by opening the Excel file).
This is the calling for Table class:
tab = Table(displayName='Table_{}'.format(table_name.replace(' ', '_')),
ref="{}:{}".format(table_start, table_end))
This is what I get:
This is what I want to get:
I search for it at OpenPyXL Docs but find only adding that filtering...
There is any way to remove this?
Many thanks!
wb = load_workbook(filename="data.xlsx")
ws = wb["Sheet1"]
ws.auto_filter.ref = None
for i in range(2, ws.max_row + 1):
ws.row_dimensions[i].hidden = False
wb.save("data.xlsx")
I just ran across this and here is how I solved it.
#Opens the file
wb = load_workbook(filename = 'somefile')
#Set worksheet
ws = wb['sheetname'] # Tab name
#set table
tbl = ws.tables["tablename"]
#removes all filters
tbl.autoFilter.filterColumn.clear()
helo,
tab = Table( displayName='Table_{}'.format(table_name.replace(' ', '_'))
, ref="{}:{}".format(table_start, table_end)
, headerRowCount = 0 # default is 1
)

openpyxl LineChart appears empty after adding reference to values

I have the following code to create a line chart in Excel using openpyxl. The problem is that when the excel file is generated, the chart container is added to the worksheet, but it is empty and no chart is displayed. I've checked the reference object and looks fine. Any idea of what could be causing this?
c1 = LineChart()
c1.title = "Line Chart"
c1.style = 10
c1.y_axis.title = 'Utilization'
c1.x_axis.title = 'Month'
data = Reference(worksheet, min_col = 2, min_row = 2, max_col = 2, max_row = 10)
print(data) #this prints Sheet 1!$B$2:$B$10
c1.add_data(data)
worksheet.add_chart(c1, "E2")
I had very similar issue with openpyxl. It turned out to be a hyphen character ('-') in the worksheet name which used later in the x and y data reference for series. I replaced the hyphen with underscore ('_') character and it worked.
In your case replace the space in the worksheet name, or add single quotes before and after sheet name, i.e. 'Sheet 1'
ws = wb.create_sheet(title = work_sheet_name.replace('-', '_'))

Copy data from excel to excel with openpyxl

Couldn't find answers I can understand. So I've decided to ask.
I'm learning Python. And now I'm trying to solve a problem with collecting data from active spreadsheet in one excel file and paste it to another excel file. The first file contains table and a few cells with information to the right of it. I'm trying to fully copy the spreadsheet data.
import openpyxl, os
from openpyxl.cell import get_column_letter
os.chdir('D:\\Python')
wb = openpyxl.load_workbook('auto.xlsx')
ws = wb.active
# Create new workbook and chose active worksheet.
wbNew = openpyxl.Workbook()
wsNew = wbNew.active
# Loop through all cells (rows, then columns) in the first file
# and fill in the second one.
for allObj in ws['A1':get_column_letter(ws.max_column) + str(ws.max_row)]:
for cellObj in allObj:
for allNewObj in wsNew:
for newCellObj in allNewObj:
wsNew[cellObj.coordinate].value = cellObj.value
wbNew.save('example.xlsx')
Finally it works.

Resources