I have multiple txt files which I am able to merge and write into different excel sheets by the below code:
for file in list(file_lists):
filename = os.path.join(path, file)
df = pd.read_table(filename,sep="|",encoding = "ISO-8859-1")
df.to_excel(writer, sheet_name=file[:-4], index=False,header=True)
writer.save()
I want to now create another sheet (Name = "Homepage") which will contain different sheet names as hyperlinks. I should be able to click on that hyperlink which will take me to the respective sheets. Is there any way I can do that? Any sample codes would be helpful, the similar codes available in SO are not helping me.
This is not really a pandas question, as the pandas.to_excel function has very little to do with the formatting and markup used in the excel sheet.
You can look at xlsxwriter which specifically formats xlsx files.
This is a sample code for formatting hyperlinks, it is adapted from the documentation where you can read more.
###############################################################################
#
# Example of how to use the XlsxWriter module to write hyperlinks
#
# Copyright 2013-2018, John McNamara, jmcnamara#cpan.org
#
import xlsxwriter
# Create a new workbook and add a worksheet
workbook = xlsxwriter.Workbook('hyperlink.xlsx')
worksheet = workbook.add_worksheet('Hyperlinks')
# Format the first column
worksheet.set_column('A:A', 30)
# Add a sample alternative link format.
red_format = workbook.add_format({
'font_color': 'red',
'bold': 1,
'underline': 1,
'font_size': 12,
})
# Write some hyperlinks
worksheet.write_url('A1', 'http://www.python.org/') # Implicit format.
worksheet.write_url('A3', 'http://www.python.org/', string='Python Home')
worksheet.write_url('A5', 'http://www.python.org/', tip='Click here')
worksheet.write_url('A7', 'http://www.python.org/', red_format)
worksheet.write_url('A9', 'mailto:jmcnamara#cpan.org', string='Mail me')
# Write a URL that isn't a hyperlink
worksheet.write_string('A11', 'http://www.python.org/')
workbook.close()
Related
I'm trying to use python to replace the contents of a sheet in an existing Excel workbook by importing data from a CSV. Ideally refreshing any pivot tables with the new data too.
How could I go about doing this?
excel_file = r'S:\Andy\Python\Monthly Report.xlsx'
sheet_name = r'Raw Data'
csv_path = r'S:\Andy\Python\Data Export.csv'
I'm trying to create a excel file with url link in a specific column.
Like this
def fill_table(table):
if elapsed_time > datetime.timedelta(minutes=args.mtime):
table.loc[len(table)] = [hostname, int(trigger_id), description, eventStartDate, eventEndDate, elapsed_time, message, useralias, link]
...
writer = pd.ExcelWriter(args.output, engine='xlsxwriter')
I tried to use the excel hyperlink formula in the link variable
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\"; \"{3}\")'.format(args.url, trigger_id,event['eventid'], event['name'])
But I get a error message when open the file and the column 'link' fill with zero's
Probably you need a comma (,) instead of a semi-colon (;) in the formula. This is because Excel stores formulas in US-style syntax (see Non US Excel functions and syntax in the XlsxWriter docs).
When I run your formula through XlsxWriter I get an Excel warning about "We found a problem with some content in 'demo.xlsx'" and when I click on "yes" to recover the formula is zero, as your described.
Changing the semi-colon to a comma makes the program work without warning and as expected:
import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\", \"{3}\")'.format('www.foo.com', 'abc', 'def', 'event1')
worksheet.write('A1', link)
# Or with a hyperlink format.
url_format = workbook.get_default_url_format()
worksheet.write('A2', link, url_format)
workbook.close()
Output:
Use xlwt which has a formula module which will store as a formula object in your dataframe.
You can then write this to excel with pandas using df.to_excel like so:
import xlwt
... # your other code here
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\"; \"{3}\")'.format(args.url, trigger_id,event['eventid'], event['name'])
excel_formatted = xlwt.Formula(link)
Then when this is passed to excel it should appear as the formula of whatever passed. I only tested it with the LEN() function but it worked fine.
I have converted a pandas DataFrame to an Excel sheet using df.to_excel.
Now, I want to add hyperlinks to the values in one column. In other words, when a customer sees my excel sheet, he would be able to click on a cell and bring up another sheet on the excel document (i dont want to bring up a website !!)
The fully reproducible example provided below demonstrates how you would create a workbook, in which you are able to click on a particular cell and bring up another sheet in the same excel document.
In this example we use Xlswriter as the engine= parameter in pandas.DataFrame.to_excel(). This done to make use of some methods in the worksheet class of Xlsxwriter library, including worksheet.write_url()(link to docs).
import pandas as pd
import numpy as np
# Creating a dataframe
df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name='data')
workbook = writer.book
worksheet = workbook.add_worksheet('sheetWithLink')
worksheet.write_url('A1', 'internal:data!A1')
worksheet.write('A1', "A link to another sheet")
writer.save()
Expected Output:
I have a requirement to read an xlsm file and update some of the sheets in the file. I want to use pandas for this purpose.
I tried answers presented in the following post. I couldn't see the VBA macros when I add the VBA project back.
https://stackoverflow.com/posts/28170939/revisions
Here are the steps I tried,
Extracted the VBA_project.bin out of the original.xlsm file and then
writer = pd.ExcelWriter('original.xlsx', engine='xlsxwriter')
workbook = writer.book
workbook.filename = 'test.xlsm'
workbook.add_vba_project('vbaProject.bin')
writer.save()
With this I don't see the VBA macros attached to "test.xlsm". The result is the same even if I write it to the "original.xlsm" file.
How do I preserve the VBA macros or add them back to the original xlsm file?
Also, is there a way I can open the "xlsm" file itself rather than the "xlsx" counterpart using pd.ExcelWriter?
You can do this easily with pandas
import pandas as pd
import xlrd
# YOU MUST PUT sheet_name=None TO READ ALL CSV FILES IN YOUR XLSM FILE
df = pd.read_excel('YourFile.xlsm', sheet_name=None)
# prints all sheets
print(df)
Ah, I see. I still can't tell what you are doing, but here are a few general samples of code to get Python to communicate with Excel.
Read contents of a worksheet in Excel:
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
df = pd.read_excel('C:\\your_path\\test.xls', sheetname='Sheet1')
************************************************************************************
Use Python to run Macros in Excel:
import os
import win32com.client
#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\your_path\excelsheet.xlsm") #opens workbook in readonly mode.
#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname")
#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit()
#Cleanup the com reference.
del xl
Write, from Python, to Excel:
import xlsxwriter
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:/your_path/ranges_and_offsets.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})
# Write some simple text.
worksheet.write('A1', 'Hello')
# Text with formatting.
worksheet.write('A2', 'World', bold)
# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
workbook.close()
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
# Data can be assigned directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("C:\\your_path\\sample.xlsx")
I didn't find anything that enable me to write comments on some specific cell while writing excel sheet using panadas.to_excel . Any help is appreciated.
After searching for some time, I think the best way to handle comments or other such properties like color and size of text at cell or sheet level is to use XlsxWriter with pandas.
Here is the link to the some nice examples of using XlsxWriter with pandas:
http://xlsxwriter.readthedocs.org/working_with_pandas.html
My reputation is too low to write a comment...
The given link by Randhawa does not provide any information about how to add comments. You can refer to this link https://xlsxwriter.readthedocs.io/working_with_cell_comments.html, which specifies how you can add comments with XlsxWriter.
worksheet.write('A1', 'Hello')
worksheet.write_comment('A1', 'This is a comment')
This is a working example based on the useful web pages linked to by Randhawa and Carsten:
import pandas as pd
# Create a Pandas dataframe
df = pd.DataFrame({"Data": [10, 20, 30, 20, 15, 30, 45]})
# Create a Pandas Excel writer using XlsxWriter as the engine
writer = pd.ExcelWriter("pandas_simple.xlsx", engine="xlsxwriter")
# Convert the dataframe to an XlsxWriter Excel object (sheet)
df.to_excel(writer, sheet_name="Sheet1")
# Get the xlsxwriter object for the sheet where you will write a comment
workbook = writer.book
worksheet = writer.sheets["Sheet1"]
# Add comment to cell A1 in worksheet ("Sheet1"), set to visible
worksheet.write_comment("A1", "This is a comment", {"visible": True})
# Write the data (sheets) to the workbook
writer.close()