8
votes

While writing the pandas code that writes dataframe to Excel.

import pandas as pd

df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

I am getting this error:

File "/usr/local/lib64/python2.7/site-packages/pandas/io/excel.py", line 1934, in __init__
import xlsxwriter
ImportError: No module named xlsxwriter

Do I need to import xlsxwriter module explicitly in the python file?

2
Yes. You need to install it separately using pip install xlsxwriterAmir Imani
Please fix formatting in your question (indentation and parethesis).dzang
@dzang updated and fixed formattingDev
@AmirhosImani: Explicit import should not be necessary, but it needs to be installed properly (--> manually).albert
@albert correct. I also meant you need to install it - no need to explicitly import in your scriptAmir Imani

2 Answers

13
votes

Install the missing module xlsxwriter manually by running

pip install xlsxwriter

After the module is installed properly, you do not need to import in manually since it will be imported as an dependency of pandas.


Remark: Summarizing the answer from the comments given below the question as discussed here and here

2
votes

always first check the # pip list, where you can see the list of packages installed on system.

now be sure >>>> pip install XlssWriter (case sensitive)

next go to your IDE >> just try

#import xlsxwriter(no case sensitive).

here is the sample script for your reference:

import xlsxwriter

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()

# Some data we want to write to the worksheet.
expenses = (
    ['Rent', 1000],
    ['Gas',   100],
    ['Food',  300],
    ['Gym',    50],
)

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# Iterate over the data and write it out row by row.
for item, cost in (expenses):
    worksheet.write(row, col,     item)
    worksheet.write(row, col + 1, cost)
    row += 1

# Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')

workbook.close()