Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No module named xlsxwriter error while writing pandas df to excel

Tags:

python

pandas

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?

like image 275
Dev Avatar asked Mar 21 '19 12:03

Dev


Video Answer


2 Answers

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

like image 136
albert Avatar answered Sep 25 '22 02:09

albert


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()
like image 32
Anil kumar Avatar answered Sep 23 '22 02:09

Anil kumar