Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read only visible sheets from Excel using Pandas?

I have to get some random Excel sheets where I want to read only visible sheets from those files.

Consider one file at a time, let's say I have Mapping_Doc.xls which contains 2-visible sheets and 2-hidden sheets.

As the sheets are less here, I can parse them with names like this:

Code :

xls = pd.ExcelFile('D:\\ExcelRead\\Mapping_Doc.xls')
print xls.sheet_names
df1 = xls.parse('Sheet1') #visible sheet
df2 = xls.parse('Sheet2') #visible sheet

Output:

[u'sheet1',u'sheet2',u'sheet3',u'sheet4']

How can I get only the visible sheets?

like image 284
Shivkumar kondi Avatar asked Jun 16 '17 05:06

Shivkumar kondi


People also ask

How do you read a specific Excel sheet in pandas?

To read an excel file as a DataFrame, use the pandas read_excel() method. You can read the first sheet, specific sheets, multiple sheets or all sheets. Pandas converts this to the DataFrame structure, which is a tabular like structure.

How do I hide an Excel sheet in python?

The worksheet object's hide() method makes the worksheet disappear till it is unhidden through Excel menu.

How do I read an XLSX file in pandas?

pandas. read_excel() function is used to read excel sheet with extension xlsx into pandas DataFrame. By reading a single sheet it returns a pandas DataFrame object, but reading two sheets it returns a Dict of DataFrame. Can load excel files stored in a local filesystem or from an URL.


1 Answers

Pandas uses the xlrd library internally (have a look at the excel.py source code if you're interested).

You can determine the visibility status by accessing each sheet's visibility attribute. According to the comments in the xlrd source code, these are the possible values:

  • 0 = visible
  • 1 = hidden (can be unhidden by user -- Format -> Sheet -> Unhide)
  • 2 = "very hidden" (can be unhidden only by VBA macro).

Here's an example that reads an Excel file with 2 worksheets, the first one visible and the second one hidden:

import pandas as pd

xls = pd.ExcelFile('test.xlsx')

sheets = xls.book.sheets()

for sheet in sheets:
    print(sheet.name, sheet.visibility)

Output:

Sheet1 0
Sheet2 1
like image 176
DocZerø Avatar answered Nov 04 '22 07:11

DocZerø