Git Product home page Git Product logo

xlwings / xlwings Goto Github PK

View Code? Open in Web Editor NEW
2.8K 123.0 481.0 53.1 MB

xlwings is a Python library that makes it easy to call Python from Excel and vice versa. It works with Excel on Windows and macOS as well as with Google Sheets and Excel on the web.

Home Page: https://www.xlwings.org

License: Other

Python 80.03% C++ 1.74% AppleScript 0.06% VBA 13.75% JavaScript 1.03% TypeScript 2.85% Rust 0.45% Handlebars 0.10%
python excel reporting automation googlesheets google-sheets

xlwings's Introduction

xlwings - Make Excel fly with Python!

xlwings (Open Source)

xlwings is a BSD-licensed Python library that makes it easy to call Python from Excel and vice versa:

  • Scripting: Automate/interact with Excel from Python using a syntax that is close to VBA.
  • Macros: Replace your messy VBA macros with clean and powerful Python code.
  • UDFs: Write User Defined Functions (UDFs) in Python (Windows only).

Numpy arrays and Pandas Series/DataFrames are fully supported. xlwings-powered workbooks are easy to distribute and work on Windows and macOS.

xlwings includes all files in the xlwings package except the pro folder, i.e., the xlwings.pro subpackage.

xlwings PRO

xlwings PRO offers additional functionality on top of xlwings (Open Source), including:

  • xlwings Server: No local Python installation required, supports Excel on the web and Google Sheets in addition to Excel on Windows and macOS. Integrates with VBA, Office Scripts and Office.js and supports custom functions on all platforms.
  • xlwings Reports: the flexible, template-based reporting system
  • xlwings Reader: A faster and more feature-rich alternative for pandas.read_excel() (no Excel installation required)
  • Easy deployment via 1-click installer and embedded code
  • See the full list of PRO features

xlwings PRO is source available and dual-licensed under one of the following licenses:

License Key

To use xlwings PRO, you need to install a license key on a Terminal/Command Prompt like so (alternatively, set the env var XLWINGS_LICENSE_KEY:

xlwings license update -k YOUR_LICENSE_KEY

See the docs for more details.

License key for noncommercial purpose:

  • To use xlwings PRO for free in a noncommercial context, use the following license key: noncommercial.

License key for commercial purpose:

  • To try xlwings PRO for free in a commercial context, request a trial license key: https://www.xlwings.org/trial
  • To use xlwings PRO in a commercial context beyond the trial, you need to enroll in a paid plan (they include additional services like support and the ability to create one-click installers): https://www.xlwings.org/pricing

xlwings PRO licenses are developer licenses, are verified offline (i.e., no telemetry/license server involved) and allow royalty-free deployments to unlimited internal and external end-users and servers for a hassle-free management. Deployments use deploy keys that don't expire but instead are bound to a specific version of xlwings.

xlwings's People

Contributors

arkottke avatar cel4 avatar chanhosuh avatar colin-b avatar danguetta avatar dependabot[bot] avatar efreeway avatar ericremoreynolds avatar fzumstein avatar gdementen avatar hiiwave avatar jb-delafosse avatar jerronl avatar kgrudzin avatar knmaki avatar kvdogan avatar ludaavics avatar njwhite avatar philipdp123 avatar pluckerpluck avatar sbremer avatar schoolie avatar sdementen avatar sebix avatar securecommi avatar timgates42 avatar wkschwartz avatar y2kbugger avatar yuyueugene84 avatar zoquda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xlwings's Issues

Win: Protected View causes file to close and reopen

When the samples are downloaded from the internet and depending on the Excel setting under File > Options > Trust Center > Trust Center Settings..., Excel can give you a Security Warning - Enable Content. If that is the case, the excecution of the macro will end with hiding the Workbook completely. In that case, only a restart of Excel helps. A workaround is to close/reopen the Workbook just after enabling the Security Warning.

Read in Excel Rows or Columns as 1dimensional lists and arrays.

When reading in horizontal/vertical Excel Ranges, xlwings currently returns a nested ("2d") list:

[[1,2,3,4]]

They should be returned as flat list using something like:

[item for sublist in l for item in sublist]

in order to get:

[1,2,3,4]

Same actually for vertical lists [[1],[2]] and for numpy arrays.

Add argument atleast_2d to force 2d behaviour.

Offset Cell Property

First of all, thanks for such amazing library. I am looking forward to having this useful module as comprehensive and soon as possible. I am kinda new to Python, mostly I am using Excel-Python Integration. I tried to put some functions I am using alot.
They worked nice for me so far. I hope I could help somehow.
Cheers

Offset * I have put this code under main.Range*

def offset(self,row,col):
    return Range(xlplatform.get_worksheet_name(self.xl_sheet),
                (self.row1+row, self.col1+col), **self.kwargs)

Color

**Codes in _xlwindows.py**
def set_color(xl_range,color_name_or_number):
    all_colors = {'black':1,
                  'white':2,
                  'red':3,
                  'green':4,
                  'blue':5,
                  'yellow':6,
                  'magenta':7,
                  'cyan':8,
                  'purple':13,
                  'orange':46,
                  'brown':53,
                  '':-4142}
    try:
        xl_range.Interior.ColorIndex = all_colors[color_name_or_number]
    except KeyError:
        xl_range.Interior.ColorIndex = color_name_or_number

def get_color(xl_range):
    color_codes = {1: 'black',
                   2: 'white',
                   3: 'red',
                   4: 'green',
                   5: 'blue',
                   6: 'yellow',
                   7: 'magenta',
                   8: 'cyan',
                   13: 'purple',
                   46: 'orange',
                   53: 'brown',
                   -4142:''}
    try:
        return color_codes[xl_range.Interior.ColorIndex]
    except KeyError:
        return xl_range.Interior.ColorIndex
------------------------------------------------------------------------------------------------------------
**Codes in main.Range**
    @property                 
    def color(self):
        """
        Sets and Gets color for given Range
        Available colors:   black, white, red, green, blue, yellow, 
                            magenta,cyan, purple, orange, brown     
        """
        return xlplatform.get_color(self.xl_range)

    @color.setter
    def color(self, color_name_or_number):
        xlplatform.set_color(self.xl_range, color_name_or_number) 

Worksheet Functions

**Codes in main.Workbook**
    def add_worksheet(self,worksheet_name = ''):
        if not worksheet_name.lower() in list(map(
        lambda x:x.lower(),xlplatform.sheet_list(self.xl_workbook))):
            xlplatform.new_worksheet(self.xl_workbook, worksheet_name)
        else:
            raise Exception("Sheetname '{}', with case ignored, is already in use."
            .format(worksheet_name))

    def remove_sheet(self, sheetname):
        xlplatform.delete_worksheet(self.xl_workbook,sheetname)


    def all_sheets(self):
        return xlplatform.sheet_list(self.xl_workbook)
---------------------------------------------------------------------------------------------------------
**Codes in _xlwindows.py
def new_worksheet(xl_workbook,worksheet_name):
    sheet_count = xl_workbook.Worksheets.Count    
    if worksheet_name == '':        
        xl_sheet = xl_workbook.Worksheets.Add (After=xl_workbook.Worksheets(sheet_count))
    else:
        xl_sheet = xl_workbook.Worksheets.Add (After=xl_workbook.Worksheets(sheet_count))
        xl_sheet.Name = worksheet_name
    return xl_sheet

def delete_worksheet(xl_workbook, sheetname):
    xl_workbook.Application.DisplayAlerts = False    
    xl_workbook.Sheets(sheetname).Delete()

def sheet_list(xl_workbook):
    z = []
    sheet_count = xl_workbook.Worksheets.Count
    for i in range(1,sheet_count+1):
        z.append(xl_workbook.Worksheets(i).Name)
    return z

Optionally show warnings, not just errors in the popup

stderr includes warnings. Windows checks for the ErrorCode - if it is 0, then no log are shown even though it may contain warnings. Mac checks for the content of the file, that's why for Mac, they are muted on using python -W ignore foo.py.

Allow to set the Working Directory in the settings

For now add a comment to the docs that path should always be fully qualified. When called from VBA, the current working directory is changed into the path of where the Python interpreter lives except the default installation is used (as otherwise, depending on the installation, a certain pywin dll isn't found) while the source file path is being appended. This means, that things like f = open('workfile', 'w') don't work anymore without specifying the fully qualified path for workfile.

Remains to be seen if we can make pywin32 reliably work for all installations without being in the Python root directory.

when passing large numbers to excel from a pandas dataframe, xlwings truncates the values

I tried to send a pandas dataframe to excel using xlwings and the elements of the dataframe are getting truncated. Here is a toy example:

import pandas as pd
from xlwings import Workbook, Range

wb = Workbook()

mydata = {'00': [0.000000e+00, 1.133106e+08, 1.112194e+08], '01': [0.000000e+00, 1.125851e+08, 1.104678e+08], '02': [0.000000e+00, 1.118832e+08, 1.113757e+08]}
mymonth = [0, 1, 2]
mydf = pd.DataFrame(data=mydata, index=mymonth)

Range("A1").value = mydf

I'm using:

  • python 2.7.6 32bits
  • xlwings 0.1.0
  • pandas 0.13.1
  • numpy 1.8.0
  • MS Excel 2007

numpy.int32/numpy.int64 are not correctly handled

TypeError: Objects of type 'numpy.int32' can not be converted to a COM VARIANT (but obtaining the buffer() of this object could).

Seems to be OK on >=1.8.0, not sure what the real problem is, but converting it using np.asscalar() works.

Check additionally for None when checking for single cells

Otherwise, something like [None, None] causes an Error when written to Excel.

Correct Line 472 and possibly other ocurrencies (TODO: factor out the check for single cells).

# Simple Lists: Turn into list of lists
if isinstance(data, list) and (isinstance(data[0], (numbers.Number, string_types, time_types) or data[0] is None):

Handling of string-formatted numbers

E.g. when the python string "01" gets written over to Excel, it's being automatically turned into a the number 1. The python string format on Excel should probably be (optionally) enforced.

Docs: Add best practice section

Mimimize number of I/O operations:
E.g. don't do Range('A1').value = 'Header 1' and Range('A2').value = 'Header 2' but Range('A1').value = ['Header 1', 'Header 2']

handle nan even if Numpy is not available

Currently, nan's are only handled (i.e. converted to a blank cell) if NumPy is installed. Since you can do:

float('nan')

It should also be handled using the builtin

math.isnan()

ImportError: DLL load failed: The specified module could not be found.

Using Enthought Canopy (which may be to blame, not sure though):

pywin32 installed properly, excel 2013 on windows 7


ImportError Traceback (most recent call last)
in ()
----> 1 from xlwings import Worbook, Range, Chart

C:\Users\porkypine\AppData\Local\Enthought\Canopy\User\lib\site-packages\xlwings__init__.py in ()
9 # Platform specific imports
10 if sys.platform.startswith('win'):
---> 11 import xlwings._xlwindows as xlplatform
12 else:
13 import xlwings._xlmac as xlplatform

C:\Users\porkypine\AppData\Local\Enthought\Canopy\User\lib\site-packages\xlwings_xlwindows.py in ()
3
4 import datetime as dt
----> 5 import win32api # needed as first import to find all dlls
6 import pywintypes
7 import pythoncom

ImportError: DLL load failed: The specified module could not be found.

Produce more user-friendly error messages

E.g. if the sheetname is misspelled, the current error is:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352565), None)

this can be decoded like this:

import win32api
win32api.FormatMessage(-2147352565)

proc.name is a string, not a function (in is_excel_running())

Just following the example in the README. Changing proc.name() to proc.name fixes the problem. Python 2.7 (Anaconda) on OS X.

 In [1]: from xlwings import Workbook, Range, Chart
 In [2]: wb=Workbook()
 ---------------------------------------------------------------------------
 TypeError                                 Traceback (most recent call last)
 <ipython-input-2-fa7edd33f875> in <module>()
 ----> 1 wb=Workbook()

 /Users/pwang/anaconda/lib/python2.7/site-packages/xlwings/main.pyc in __init__(self, fullname)
      68         else:
      69             # Open Excel if necessary and create a new workbook
 ---> 70             self.xl_app, self.xl_workbook = xlplatform.new_workbook()
      71
      72         self.name = xlplatform.get_workbook_name(self.xl_workbook)

 /Users/pwang/anaconda/lib/python2.7/site-packages/xlwings/_xlmac.pyc in new_workbook()
      73
      74 def new_workbook():
 ---> 75     is_running = is_excel_running()
      76
      77     xl_app = app('Microsoft Excel')

 /Users/pwang/anaconda/lib/python2.7/site-packages/xlwings/_xlmac.pyc in is_excel_running()
      30 def is_excel_running():
      31     for proc in psutil.process_iter():
 ---> 32         if proc.name() == 'Microsoft Excel':
      33             return True
      34     return False

 TypeError: 'str' object is not callable

Object design for Workbook qualification

Should it really be wb.range('Sheet1', 'A1').value or would something like Range('Sheet1', 'A1', workbook=wb) be more Pythonic? The advantage would be that we could use classmethods for Chart.add() instead of Chart().add(), for example. Also, classes would always be classes (e.g. Range) and not turn into methods (wb.range).

Allow to write out lists in vertical orientation to Excel

This will be very handy for 1d arrays/lists. If you want to write out a 1d NumPy array in column orientation you currently have to do something like this for 1d arrays:

Range('A1').value = 1d_array[:,np.newaxis]

It should be easier like this:

Range('A1').vertical.value = 1d_array

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.