當前位置: 首頁>>代碼示例>>Python>>正文


Python xlrd.open_workbook方法代碼示例

本文整理匯總了Python中xlrd.open_workbook方法的典型用法代碼示例。如果您正苦於以下問題:Python xlrd.open_workbook方法的具體用法?Python xlrd.open_workbook怎麽用?Python xlrd.open_workbook使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在xlrd的用法示例。


在下文中一共展示了xlrd.open_workbook方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_read_xlrd_book

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def test_read_xlrd_book(self, ext):
        import xlrd
        df = self.frame

        engine = "xlrd"
        sheet_name = "SheetA"

        with ensure_clean(ext) as pth:
            df.to_excel(pth, sheet_name)
            book = xlrd.open_workbook(pth)

            with ExcelFile(book, engine=engine) as xl:
                result = read_excel(xl, sheet_name, index_col=0)
                tm.assert_frame_equal(df, result)

            result = read_excel(book, sheet_name=sheet_name,
                                engine=engine, index_col=0)
            tm.assert_frame_equal(df, result) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:test_excel.py

示例2: translate_to

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def translate_to():
	post = []

	book = open_workbook(sys.argv[1])
	sheet = book.sheet_by_index(0)
	ctr = 0
	for row in sheet.col(1):
		if ctr!=0:
			post.append(row.value.encode('utf-8'))
		ctr+=1
	for i in range(0,len(post)):
		str(post[i])


	translations=[] 
	xbook = xlsxwriter.Workbook('hinglish.xlsx')
	xsheet = xbook.add_worksheet('Test')
	for i in range(0,len(post)):
		translation = translator.translate(post[i],src='en', dest='hi')
		xsheet.write(i,1,''.join((translation.text))) 
開發者ID:vipul-khatana,項目名稱:Hinglish-Sentiment-Analysis,代碼行數:22,代碼來源:algo.py

示例3: xls_as_xlsx

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def xls_as_xlsx(xls_file):
    # first open using xlrd
    source_workbook = xlrd.open_workbook(file_contents=xls_file.read())

    # Create the destination workbook, deleting and auto-generated worksheets.
    destination_workbook = openpyxl.Workbook() # TODO: Would like to figure out how to make appends work with a "write_only" workbook.
    for wksht_nm in destination_workbook.get_sheet_names():
        worksheet= destination_workbook.get_sheet_by_name(wksht_nm)
        destination_workbook.remove_sheet(worksheet)

    worksheet_names= ['survey', 'choices']
    for wksht_nm in source_workbook.sheet_names():
        source_worksheet= source_workbook.sheet_by_name(wksht_nm)
        destination_worksheet= destination_workbook.create_sheet(title=wksht_nm)

        for row in xrange(source_worksheet.nrows):
            destination_worksheet.append( [source_worksheet.cell_value(row, col) for col in xrange(source_worksheet.ncols)] )

    return io.BytesIO(save_virtual_workbook(destination_workbook)) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:21,代碼來源:analyser_export.py

示例4: test_read_xlrd_Book

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def test_read_xlrd_Book(self):
        _skip_if_no_xlrd()
        _skip_if_no_xlwt()

        import xlrd

        df = self.frame

        with ensure_clean('.xls') as pth:
            df.to_excel(pth, "SheetA")
            book = xlrd.open_workbook(pth)

            with ExcelFile(book, engine="xlrd") as xl:
                result = xl.parse("SheetA")
                tm.assert_frame_equal(df, result)

            result = read_excel(book, sheetname="SheetA", engine="xlrd")
            tm.assert_frame_equal(df, result) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:20,代碼來源:test_excel.py

示例5: convert_xls_to_xlsx

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def convert_xls_to_xlsx(src_file_path, dst_file_path):

    print (src_file_path, dst_file_path)
    book_xls = xlrd.open_workbook(src_file_path)
    book_xlsx = Workbook()

    sheet_names = book_xls.sheet_names()
    for sheet_index in range(0,len(sheet_names)):
        sheet_xls = book_xls.sheet_by_name(sheet_names[sheet_index])
        if sheet_index == 0:
            sheet_xlsx = book_xlsx.get_active_sheet()
            sheet_xlsx.title = sheet_names[sheet_index]
        else:
            sheet_xlsx = book_xlsx.create_sheet(title=sheet_names[sheet_index])

        for row in range(0, sheet_xls.nrows):
            for col in range(0, sheet_xls.ncols):
                sheet_xlsx.cell(row = row+1 , column = col+1).value = sheet_xls.cell_value(row, col)

    book_xlsx.save(dst_file_path)
    return dst_file_path 
開發者ID:italia,項目名稱:anpr,代碼行數:23,代碼來源:create_sphinx_tables.py

示例6: read_context_from_excel

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def read_context_from_excel(filename):
    if not os.path.exists(filename):
        return []
    
    arr = []
    workbook = xlrd.open_workbook(filename=filename)
    for sheetname in workbook.sheet_names():
        sheet = workbook.sheet_by_name(sheetname)
        cur_sheet = []
        for i in range(sheet.nrows):
            rows = []
            for j in range(sheet.ncols):
                rows.append(get_cell_val(sheet, i, j, datemode=workbook.datemode))
            cur_sheet.append(rows)
        arr.append(cur_sheet)
    return arr 
開發者ID:SmileJET,項目名稱:utils-for-python,代碼行數:18,代碼來源:handle_excel.py

示例7: process

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def process():
    book = xlrd.open_workbook(file_contents=requests.get(URL).content)
    sheet = book.sheet_by_index(0)

    return [
        {
            "country_code": "FI",
            "primary": True,
            "bic": bic.value.upper().strip(),
            "bank_code": bank_code.value,
            "name": name.value,
            "short_name": name.value,
        }
        for bank_code, bic, name in list(sheet.get_rows())[2:]
        if bank_code.value != ""
    ] 
開發者ID:mdomke,項目名稱:schwifty,代碼行數:18,代碼來源:get_bank_registry_fi.py

示例8: process

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def process():
    registry = []
    skip_names = ["NAV", "VRIJ", "NAP", "NYA", "VRIJ - LIBRE", "-"]

    book = xlrd.open_workbook(file_contents=requests.get(URL).content)
    sheet = book.sheet_by_index(0)

    for row in list(sheet.get_rows())[2:]:
        bank_code, bic, name, second_name = row[:4]
        if bic.value.upper() in skip_names:
            continue
        registry.append(
            {
                "country_code": "BE",
                "primary": True,
                "bic": bic.value.upper().replace(" ", ""),
                "bank_code": bank_code.value,
                "name": name.value or second_name.value,
                "short_name": name.value or second_name.value,
            }
        )
    return registry 
開發者ID:mdomke,項目名稱:schwifty,代碼行數:24,代碼來源:get_bank_registry_be.py

示例9: read_xls

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def read_xls(_file):
    agent_config_vars['data_format'] = 'CSV' # treat as CSV from here out
    agent_config_vars['timestamp_format'] = ['epoch']
    # open workbook
    with xlrd.open_workbook(_file) as wb:
        # for each sheet in the workbook
        for sheet in wb.sheets():
            # for each row in the sheet
            for row in sheet.get_rows():
                # build dict of <field name: value>
                d = label_message(list(map(lambda x: x.value, row)))
                # turn datetime into epoch
                timestamp = ''
                while timestamp == '' and len(agent_config_vars['timestamp_field']) != 0:
                    timestamp_field = agent_config_vars['timestamp_field'].pop(0)
                    try:
                        timestamp_xlrd = d[timestamp_field]
                    except KeyError:
                        continue
                    timestamp = get_timestamp_from_datetime(datetime(
                        *xlrd.xldate_as_tuple(
                            timestamp_xlrd,
                            sheet.book.datemode)))
                d[timestamp_field] = timestamp
                agent_config_vars['timestamp_field'] = [timestamp_field]
                yield d 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:28,代碼來源:getmessages_file_replay.py

示例10: census_parser

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def census_parser(filename, verbose):
    # Create the named tuple
    CensusTuple = namedtuple('Census', 'name, rank, count, prop100k, cum_prop100k, pctwhite, pctblack, pctapi, pctaian, pct2prace, pcthispanic')

    # Define the location of the file and worksheet till arguments are developed
    worksheet_name = "top1000"

    #Define work book and work sheet variables
    workbook = xlrd.open_workbook(filename)
    spreadsheet = workbook.sheet_by_name(worksheet_name)
    total_rows = spreadsheet.nrows - 1
    current_row = -1

    # Define holder for details
    username_dict = {}
    surname_dict = {}
    alphabet = list(string.ascii_lowercase)

    while current_row < total_rows:
        row = spreadsheet.row(current_row)
        current_row += 1
        entry = CensusTuple(*tuple(row)) #Passing the values of the row as a tuple into the namedtuple
        surname_dict[entry.rank] = entry
        cellname = entry.name
        cellrank = entry.rank
        for letter in alphabet:
            if "." not in str(cellrank.value):
                if verbose > 1:
                    print("[-] Eliminating table headers")
                break
            username = letter + str(cellname.value.lower())
            rank = str(cellrank.value)
            username_dict[username] = rank
    username_list = sorted(username_dict, key=lambda key: username_dict[key])

    return(surname_dict, username_dict, username_list) 
開發者ID:funkandwagnalls,項目名稱:pythonpentest,代碼行數:38,代碼來源:username_generator.py

示例11: main

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def main():
    """Run the program."""
    args = parse_arguments()

    ext = os.path.splitext(args.input_file)[-1].lower()
    with gzip.open(args.output_file, mode="wt") as outfile:
        csvwriter = csv.writer(outfile, delimiter=str("\t"), lineterminator="\n")

        try:
            if ext in (".tab", ".txt", ".tsv"):
                with open(args.input_file) as infile:
                    for line in infile:
                        outline = line.strip().split("\t")
                        csvwriter.writerow(outline)
            elif ext == ".csv":
                with open(args.input_file) as infile:
                    for line in infile:
                        outline = line.strip().split(",")
                        csvwriter.writerow(outline)
            elif ext in (".xls", ".xlsx"):
                workbook = xlrd.open_workbook(args.input_file)
                worksheet = workbook.sheets()[0]
                for rownum in range(worksheet.nrows):
                    csvwriter.writerow(worksheet.row_values(rownum))
            else:
                print('{"proc.error":"File extension not recognized."}')
        except Exception:
            print('{"proc.error":"Corrupt or unrecognized file."}')
            raise 
開發者ID:genialis,項目名稱:resolwe,代碼行數:31,代碼來源:parse_tabular_file.py

示例12: pasre_inter

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def pasre_inter(filename):#導入接口
	file=xlrd.open_workbook(filename)
	me=file.sheets()[0]
	nrows=me.nrows
	ncol=me.ncols
	project_name=[]
	model_name=[]
	interface_name=[]
	interface_url=[]
	interface_meth=[]
	interface_par=[]
	interface_header=[]
	interface_bas=[]
	jiekou_bianhao=[]
	interface_type=[]
	for i in range(2,nrows):
		jiekou_bianhao.append(me.cell(i,0).value)
		project_name.append(me.cell(i,2).value)
		model_name.append(me.cell(i,3).value)
		interface_name.append(me.cell(i,1).value)
		interface_url.append(me.cell(i,4).value)
		interface_type.append(me.cell(i,5).value)
		interface_header.append(me.cell(i,6).value)
		interface_meth.append(me.cell(i,7).value)
		interface_par.append(me.cell(i,8).value)
		interface_bas.append(me.cell(i,9).value)
		i+=1
	return jiekou_bianhao,interface_name,project_name,model_name,interface_url,\
		   interface_header,interface_meth,interface_par,interface_bas,interface_type
#導入測試用例 
開發者ID:liwanlei,項目名稱:FXTest,代碼行數:32,代碼來源:parsingexcel.py

示例13: _check_xls_export

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def _check_xls_export(self):
        xls_export_url = reverse(
            'xls_export', kwargs={'username': self.user.username,
                                  'id_string': self.xform.id_string})
        response = self.client.get(xls_export_url)
        expected_xls = open_workbook(os.path.join(
            self.this_directory, "fixtures", "transportation",
            "transportation_export.xls"))
        content = self._get_response_content(response)
        actual_xls = open_workbook(file_contents=content)
        actual_sheet = actual_xls.sheet_by_index(0)
        expected_sheet = expected_xls.sheet_by_index(0)

        # check headers
        self.assertEqual(actual_sheet.row_values(0),
                         expected_sheet.row_values(0))

        # check cell data
        self.assertEqual(actual_sheet.ncols, expected_sheet.ncols)
        self.assertEqual(actual_sheet.nrows, expected_sheet.nrows)
        for i in range(1, actual_sheet.nrows):
            actual_row = actual_sheet.row_values(i)
            expected_row = expected_sheet.row_values(i)

            # remove _id from result set, varies depending on the database
            del actual_row[22]
            del expected_row[22]
            self.assertEqual(actual_row, expected_row) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:30,代碼來源:test_process.py

示例14: _num_rows

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def _num_rows(self, content, export_format):
        def xls_rows(f):
            return open_workbook(file_contents=f).sheets()[0].nrows

        def csv_rows(f):
            with tempfile.TemporaryFile() as tmp:
                tmp.write(f.encode('utf-8'))
                tmp.seek(0)
                return len([line for line in csv.reader(tmp)])
        num_rows_fn = {
            'xls': xls_rows,
            'csv': csv_rows,
        }
        return num_rows_fn[export_format](content) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:16,代碼來源:test_form_exports.py

示例15: _get_xls_data

# 需要導入模塊: import xlrd [as 別名]
# 或者: from xlrd import open_workbook [as 別名]
def _get_xls_data(self, filepath):
        storage = get_storage_class()()
        with storage.open(filepath) as f:
            workbook = open_workbook(file_contents=f.read())
        transportation_sheet = workbook.sheet_by_name("transportation")
        self.assertTrue(transportation_sheet.nrows > 1)
        headers = transportation_sheet.row_values(0)
        column1 = transportation_sheet.row_values(1)
        return dict(zip(headers, column1)) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:11,代碼來源:test_exports.py


注:本文中的xlrd.open_workbook方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。