Kết nối mongodb với excel

Mô-đun này chuyển đổi bảng tính Excel được định dạng chính xác của bạn thành một bộ sưu tập trong cơ sở dữ liệu được chỉ định trong MongoDB

Định dạng Excel được hỗ trợ

Các định dạng Excel được hỗ trợ là XLS/XLSX/CSV

Định dạng bảng tính

Mời các bạn xem các sheet mẫu Excel được cung cấp để có cái nhìn rõ nét về File. Bảng mẫu của Microsoft

Cài đặt

npm install excel-to-mongoDB --save

thử nghiệm

git clone https://github.com/ngudbhav/excel-to-mongoDB.git
cd excel-to-mongoDB/

Điều hướng đến thư mục

cd test/
nano test.js

Bây giờ tệp này cần thông tin đăng nhập MongoDB. Cung cấp các thông tin đăng nhập đó ở định dạng Chuỗi và lưu bằng cách nhấn các phím sau

Microsoft Excel là một ứng dụng bảng tính được phát triển bởi Microsoft. Đây là phần mềm được sử dụng phổ biến nhất và nó tạo ra doanh thu hơn 1 tỷ đô la mỗi năm. Nó là một chương trình độc lập và cũng có thể được tích hợp với các phần mềm khác như Microsoft Office, cung cấp cho người dùng nhiều chức năng. Nó rất hữu ích trong việc hoàn thành các nhiệm vụ như theo dõi tài chính doanh nghiệp, tạo tài liệu, thực hiện phân tích phức tạp, v.v.

MongoDB là một cơ sở dữ liệu đa nền tảng, mã nguồn mở được phát triển bởi MongoDB Inc. Nó được xây dựng để lưu trữ dữ liệu cho các ứng dụng web và cực kỳ linh hoạt và có thể tăng hoặc giảm quy mô một cách liền mạch. Nó cho phép người dùng xây dựng các dịch vụ của riêng họ trên cơ sở dữ liệu này

Microsoft Excel chứa nhiều loại đỉnh bao gồm đỉnh biểu đồ, đỉnh quản lý ma trận, cũng như đỉnh thống kê và biểu đồ. Hai tính năng chính của phần mềm này là bảng tổng hợp và biểu đồ tổng hợp. Bảng tổng hợp giúp bạn tổ chức lại và tóm tắt dữ liệu để dễ dàng xem lại. Biểu đồ trục là biểu diễn đồ họa có thể giúp bạn phân tích dữ liệu của mình hiệu quả hơn. Excel có nhiều công dụng trong kinh doanh. Có nhiều cách có thể sử dụng nó, bao gồm lập ngân sách, dự báo, tăng hoặc giảm doanh số bán hàng, v.v.

MongoDB cung cấp giải pháp lưu trữ cho mục đích chung hơn Excel. Tuy nhiên, nó có một số chức năng chồng chéo với Excel. Cả hai đều có thể được sử dụng để tạo bảng dữ liệu nhằm giúp bạn sắp xếp dữ liệu để sử dụng trong các loại dự án khác nhau. Dữ liệu này sau đó có thể được sử dụng để tạo biểu đồ và biểu đồ, v.v. Sắp xếp dữ liệu rất quan trọng đối với các doanh nghiệp vì nó giúp dễ dàng xem các xu hướng và mẫu trong dữ liệu để có thể đưa ra quyết định từ thông tin có sẵn

Nhìn chung, Microsoft Excel và MongoDB rất giống nhau về những gì chúng làm. Cả hai đều cho phép người dùng sắp xếp và phân tích dữ liệu để hiểu rõ hơn về xu hướng và mẫu. Cả hai cũng cung cấp nhiều loại đỉnh có thể được sử dụng để vẽ biểu đồ và dữ liệu biểu đồ cũng như thực hiện các phép tính để có được những hiểu biết mới mà không thể thực hiện được nếu không sử dụng các chương trình này. Tuy nhiên, giữa chúng cũng có một số khác biệt. Ví dụ: Excel chỉ khả dụng trên PC Windows và chỉ dưới dạng một chương trình độc lập trong khi MongoDB khả dụng trên nhiều nền tảng khác nhau bao gồm Windows, Linux, Mac OS X, v.v.

Quá trình tích hợp Microsoft Excel và MongoDB có vẻ phức tạp và đáng sợ. Đây là lý do tại sao Appy Pie Connect đã đưa ra một giải pháp đơn giản, giá cả phải chăng và nhanh chóng để giúp bạn tự động hóa quy trình làm việc của mình. Bấm vào nút bên dưới để bắt đầu

Giải pháp của riêng tôi là để Python dán chúng lại với nhau bằng pymongo và win32com. Sau đó, khá đơn giản để chạy bất cứ thứ gì bạn muốn. Trong trường hợp của tôi, tôi có vòng lặp Python chỉ đơn giản là liên tục "lắng nghe" một số ô Excel nhất định, gọi những gì nó cần từ Mongo, sau đó đặt lại vào Excel. Nó linh hoạt và nhiều thứ có thể được thực hiện theo cách này. Đây là cơ sở mã đầy đủ, nhưng bạn sẽ phải thay đổi lệnh gọi thành Mongodb để phù hợp với cơ sở dữ liệu của riêng bạn. Tại đây, bạn cũng sẽ thấy một số cách nhất định để bạn có thể thay đổi màu sắc và nội dung của các ô Excel từ bên trong Python. Ồ, tôi nên đề cập rằng nó có nhiều chuỗi thoát ansi, vì vậy bạn có thể muốn chạy Python từ ansicon hoặc ConEmu

import win32com.client as win32
import time    # will need this for time parsing
from optparse import OptionParser
import pdb     # debugger, when necessary
import string  # for string parsing and the alphabet
from pymongo import MongoClient
import inspect
from datetime import datetime, timedelta, tzinfo
from dateutil import tz
from bson.son import SON
import msvcrt # for getch
import os
import sys # for stdout.write
from collections import OrderedDict


def parseCmdLine():
    parser = OptionParser(description="Retrieve realtime data.")
    parser.add_option("--f",
                      dest="file",
                      help="filename",
                      default="bbcapture.xls")
    parser.add_option("--mongohost",
                      dest="mongohost",
                      default="192.168.1.30")
    parser.add_option("--mongoport",
                      dest="mongoport",
                      type="int",
                      default=27017)

    (options, args) = parser.parse_args()
    return(options)

options = parseCmdLine() # parse the commandline
client = MongoClient(options.mongohost, options.mongoport) # link to mongo
db = client.bb # the database
bbsecs = db.bbsecs # now all the collections
bbdaily = db.bbdaily
bbticks = db.bbticks
linkstatusperiod = False # for the moving period in the top left excel cell showing we're linked

def ansi(colour = "white", bright = False, back = "black"):
# ansi colour sequences
    brit = {True:       "\033[1m",
            False:      "\033[0m"}
    colo = {"black":    "\033[30m", 
            "red":      "\033[31m",
            "green":    "\033[32m",
            "yellow":   "\033[33m",
            "blue":     "\033[34m",
            "magenta":  "\033[35m",
            "cyan":     "\033[36m",
            "white":    "\033[37m"}
    bakk = {"black":    "\033[40m", 
            "red":      "\033[41m",
            "green":    "\033[42m",
            "yellow":   "\033[43m",
            "blue":     "\033[44m",
            "magenta":  "\033[45m",
            "cyan":     "\033[46m",
            "white":    "\033[47m"}
    sys.stdout.write(brit[bright])
    sys.stdout.write(colo[colour])
    sys.stdout.write(bakk[back])


def mdaily(ticker = "USDEUR Curncy", field = "LAST_PRICE", sortdirection = 1, numget = 1000000):
    ansi("cyan", False)
    print "\nGetting", ticker, "field", field, "from Mongo...",
    lister = OrderedDict()
    #for post in bbdaily.find({"ticker": ticker, "fieldname": field}).limit(numget).sort("time", sortdirection):
    for post in bbdaily.find({"$query": {"ticker": ticker, "fieldname": field}, "$orderby": {"time": -1}}).limit(numget):
        lister[str(post["time"])] = post["fieldvalue"]
    ansi("cyan", True)
    print "got", len(lister), "values",
    ansi()
    return lister

def mtick(tickers, sortdirection = 1, numget = 1000000):
    if len(tickers) == 0:
        return []
    else:
        ansi("green", False)
        print "\n Getting minutes for for", tickers, 
        tickerdic = OrderedDict()
        for eachticker in tickers:
            eachdic = dict()
            print numget
            for post in bbticks.find({"ticker": eachticker}).limit(numget):
                eachdic[post["time"]] = [post["open"], post["high"], post["low"], post["close"]]
            ansi("green")
            tickerdic[eachticker] = eachdic
            print "got", len(eachdic), "for ticker", eachticker, 
        ansi("green", True)
        print "got", len(tickerdic), "tickers",
        dates = [set(tickerdic[x].keys()) for x in tickerdic] # get all the dates
        dates = set.intersection(*dates) # get the unique ones
        dates = [x for x in dates] # convert to list
        if sortdirection == -1:
            dates = sorted(dates, reverse = True)
        else:
            dates = sorted(dates, reverse = False)
        retlist = [[[x, tickerdic[y][x][0], tickerdic[y][x][1], tickerdic[y][x][2], tickerdic[y][x][3]] for x in dates] for y in tickerdic.keys()]
        ansi()
        return retlist

def getsecs():
    seclist = []
    for post in bbsecs.find():
        seclist.append(post["ticker"])
    return(seclist)




def offsetString(startrow, startcol, endrow, endcol):
    startrowstr = str(startrow)
    endrowstr = str(endrow)
    if(startcol > 26):
        startcolstr = string.uppercase[startcol / 26 - 1] + string.uppercase[startcol % 26 - 1]
    else:
        startcolstr = string.uppercase[startcol - 1]
    if(endcol > 26):
        endcolstr = string.uppercase[endcol / 26 - 1] + string.uppercase[endcol % 26 - 1]
    else:
        endcolstr = string.uppercase[endcol - 1]
    return(startcolstr + startrowstr + ":" + endcolstr + endrowstr)

def main():
    excel = win32.gencache.EnsureDispatch("Excel.Application")
    excel.Visible = 1
    try: # try to link to the file
        ansi("red", False)
        print "Linking to", options.file
        wb = excel.Workbooks(options.file)
        ws = wb.Worksheets("MongoData")
        ansi()
    except: # not open then try to load it
        try:
            ansi("red", False)
            print "Not open... trying to open in current directory", os.getcwd()
            ansi()
            wb = excel.Workbooks.Open(os.getcwd() + "\\" + options.file)
            ws = wb.Worksheets("MongoData")
            ansi()
        except: # can't load then ask to create it
            ansi("red", True)
            print options.file, "not found here. Create? (y/n) ",
            ansi("yellow", True)
            response = msvcrt.getch()
            print response
            ansi()
            if response.upper() == "Y":
                wb = excel.Workbooks.Add()
                ws = excel.Worksheets.Add()
                ws.Name = "MongoData"
                wb.SaveAs(os.getcwd() + "\\" + options.file)
            else: # don't wanna create it then exit
                print "bye."
                return
    # see if ticks sheet works otherwise add it
    try:
        wst = wb.Worksheets("MongoTicks")
    except:
        wst = excel.Worksheets.Add()
        wst.Name = "MongoTicks"
        wst.Cells(3, 2).Value = 1
    # see if securities list sheet works otherwise add it
    try:
        wall = wb.Worksheets("AllSecurities")
        wall.Cells(1, 1).Value = "List of all securities"
        wall.Range("A1:A1").Interior.ColorIndex = 8
        wall.Range("A:A").ColumnWidth = 22
    except:
        wall = excel.Worksheets.Add()
        wall.Name = "AllSecurities"
        wall.Cells(1, 1).Value = "List of all securities"
        wall.Range("A1:A1").Interior.ColorIndex = 8
        wall.Range("A:A").ColumnWidth = 22

    ansi("green", True)
    print "talking to", options.file, 
    ansi("green", False)
    print ".. press any key when this console has the focus, to end communication"
    ansi()
    def linkstatusupdate():
        global linkstatusperiod
        if linkstatusperiod:
            ws.Cells(1, 1).Value = "Talking to Python|"
            wst.Cells(1, 1).Value = "Talking to Python!"
            linkstatusperiod = False
        else:
            ws.Cells(1, 1).Value = "Talking to Python|"
            wst.Cells(1, 1).Value = "Talking to Python!"
            linkstatusperiod = True
        ws.Cells(1, 2).Value = datetime.now()
    # daily worksheet header formatting
    ws.Cells(1, 1).Value = "Excel linked to Python"
    ws.Cells(1, 3).Value = "Sort direction:"
    ws.Cells(1, 4).Value = 1
    ws.Cells(1, 5).Value = "Fetch max:"
    ws.Cells(2, 1).Value = "Enter tickers:"
    ws.Cells(3, 1).Value = "Start data:"
    ws.Cells(4, 1).Value = "End data:"
    ws.Range("A:A").ColumnWidth = 22
    ws.Range("B:B").ColumnWidth = 20
    ws.Range("A2:GS2").Interior.ColorIndex = 19 # beige 200 columns
    ws.Range("A3:GS4").Interior.ColorIndex = 15 # grey
    ws.Range("A2").Interior.ColorIndex = 3 # red
    ws.Range("A3:A4").Interior.ColorIndex = 16 # dark grey
    # minute worksheet header formatting
    wst.Cells(1, 1).Value = "Excel linked to Python"
    wst.Cells(2, 1).Value = "Enter tickers:"
    #wst.Cells(3, 1).Value = "Enter periodicity:"
    wst.Cells(1, 3).Value = "Sort direction:"
    wst.Cells(1, 4).Value = 1
    wst.Cells(1, 5).Value = "Fetch max:"
    wst.Range("A:A").ColumnWidth = 22
    wst.Range("B:B").ColumnWidth = 20
    wst.Range("A2:GS3").Interior.ColorIndex = 19 # beige 200 columns
    wst.Range("A4:GS5").Interior.ColorIndex = 15 # grey
    wst.Range("A2:A3").Interior.ColorIndex = 4 # red
    wst.Range("6:100000").Clear()
    linkstatusperiod = False
    oldsecd = []
    oldseci = []
    oldnumget = oldsortdir = toldnumget = toldsortdir = 0
    while not msvcrt.kbhit():
        try:
            print "...", wb.Name,
            securities = ws.Range("B2:GS2").Value[0]
            sortdir = ws.Cells(1, 4).Value
            if sortdir == None:
                sortdir = 1
            sortdir = int(sortdir)
            numget = ws.Cells(1, 6).Value
            if numget == None:
                numget = 1000000
            numget = int(numget)
            securities = [x for x in securities if x is not None]
            if not ((oldsecd == securities) and (oldnumget == numget) and (oldsortdir == sortdir)): # clear content of cells 
                ws.Range("5:1000000").Clear()
                ws.Range("B3:GS4").Clear()
                ws.Range("B3:GS4").Interior.ColorIndex = 15 # grey
                oldsecd = securities
                oldnumget = numget
                oldsortdir = sortdir
            currentcol = 0
            for sec in securities:
                linkstatusupdate()
                secdata = mdaily(sec, "LAST_PRICE", sortdir, numget)
                currentrow = 0
                vallist = []
                datelist = []
                if sortdir == -1:
                    sortedkeys = sorted(secdata, reverse = True)
                else: 
                    sortedkeys = sorted(secdata, reverse = False)
                for eachkey in sortedkeys:
                    datelist.append(eachkey)
                    vallist.append(secdata[eachkey])
                #now stick them in Excel
                ws.Range(offsetString(5 + currentrow, 2 + currentcol, 5 + currentrow + len(vallist) - 1, 2 + currentcol)).Value = \
                        tuple([(x, ) for x in vallist])
                if currentcol == 0:
                    ws.Range(offsetString(5 + currentrow, 1, 5 + currentrow + len(vallist) - 1, 1)).Value = \
                        tuple([(x, ) for x in datelist])
                if len(sortedkeys) > 0:
                    ws.Cells(3, 2 + currentcol).Value = sortedkeys[len(sortedkeys) - 1].split()[0] # start data date
                    ws.Cells(4, 2 + currentcol).Value = sortedkeys[0].split()[0] # end data date
                currentcol += 1
            # now do the tick data
            securitiest = wst.Range("B2:GS2").Value[0]
            securitiest = [x for x in securitiest if x is not None]
            tsortdir = wst.Cells(1, 4).Value
            if tsortdir == None:
                tsortdir = 1
            tsortdir = int(tsortdir)
            tnumget = wst.Cells(1, 6).Value
            if tnumget == None:
                tnumget = 1000000
            tnumget = int(tnumget)
            if not ((oldseci == securitiest) and (toldnumget == tnumget) and (toldsortdir == tsortdir)): # clear the contents of the cells 
                wst.Range("6:1000000").Clear()
                wst.Range("B4:GS5").Clear()
                wst.Range("B4:GS5").Interior.ColorIndex = 15 # grey
                oldseci = securitiest
                toldnumget = tnumget
                toldsortdir = tsortdir
            secdata = mtick(securitiest, tsortdir, tnumget)
            currentsec = 0
            for x in secdata:
                sender = [tuple(y[1:5]) for y in x]
                wst.Range(offsetString(6, 2 + currentsec * 4, 6 + len(x) - 1, 5 + currentsec * 4)).Value = sender
                if currentsec == 0: # then put the dates in 
                    dates = [tuple([y[0], ]) for y in x]
                    wst.Range(offsetString(6, 1, 6 + len(x) - 1, 1)).Value = dates
                wst.Range(offsetString(5, 2 + currentsec * 4, 5, 5 + currentsec * 4)).Value = ["open", "high", "low", "close"]
                currentsec += 1
            for x in range(0, len(securitiest)):
                wst.Cells(4, 2 + x * 4).Value = securitiest[x]
            linkstatusupdate()
            allsecs = tuple([(yy, ) for yy in getsecs()])
            wall.Range(offsetString(2, 1, len(allsecs) + 1, 1)).Value = allsecs

        except:
            print "\nExcel busy",
        time.sleep(1)

    endchar = msvcrt.getch() # capture the last character so it doesn't go to console
    print "\nbye."


if __name__ == "__main__":
    main()

Tôi có thể liên kết cơ sở dữ liệu với Excel không?

Để kết nối Excel với cơ sở dữ liệu trong Cơ sở dữ liệu SQL, hãy mở Excel rồi tạo sổ làm việc mới hoặc mở sổ làm việc Excel hiện có. Trong thanh menu ở đầu trang, chọn tab Dữ liệu, chọn Lấy dữ liệu, chọn Từ Azure, sau đó chọn Từ Cơ sở dữ liệu Azure SQL

MongoDB có thể lưu trữ tệp Excel không?

MongoDB không hỗ trợ nhập trực tiếp các tệp Excel , vì vậy, để làm điều đó, chúng tôi sẽ sử dụng một hàm được tích hợp sẵn trong Excel.

Excel có thể lấy dữ liệu từ cơ sở dữ liệu không?

Bạn cũng có thể nhập dữ liệu vào Excel dưới dạng bảng hoặc báo cáo PivotTable . Chọn Dữ liệu > Nhận dữ liệu > Từ cơ sở dữ liệu > Từ cơ sở dữ liệu dịch vụ phân tích máy chủ SQL (Nhập).

Làm cách nào để trích xuất dữ liệu từ MongoDB?

Vì vậy, để xuất dữ liệu từ cơ sở dữ liệu MongoDB, MongoDB cung cấp một công cụ dòng lệnh được gọi là mongoexport . Sử dụng công cụ này, bạn có thể xuất dữ liệu của bộ sưu tập ở định dạng JSON hoặc CSV (giá trị được phân tách bằng dấu phẩy). Hơn nữa, chúng tôi cũng có thể sử dụng các tính năng như giới hạn và sắp xếp trên bộ sưu tập trong khi xuất dữ liệu.