Beispiel #1
0
 def init(self):
     self.excel = Excel()
     path = 'C:/Users/yyw/Desktop/study/환시스/lottesuper.xlsx'
     self.excel.get_execel(path)
     self.excel.get_sheet('Sheet1')
     self.total = 0.0
     self.i = 1
    def test_read_header(self):
        """Lectura de encabezados de archivo excel"""
        xl = Excel()
        data = xl.read_file("samplexl.xlsx", "datosm")
        headers = ("Nombre", "App", "Apm")

        self.assertEqual(xl.get_headers(), headers)
Beispiel #3
0
    def goto_find(self):
        print('++++++++++++++++++++\n', 'debug', '\n')
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setRowCount(2)
        #  j = 0  # 第几行(从0开始)
        #  i = 0  # 第几列(从0开始)
        # Value = "test"  # 内容
        #self.tableWidget.setItem(i, j, QTableWidgetItem(Value))  # 设置j行i列的内容为Value

        #excel.py处理单个sheet有内存溢出bug,暂时直接用
        str = self.find_text.toPlainText()  #获取text的文本内容
        print(str)
        excel = Excel(file_path)
        excel.read_sheet_data(str)
        #print(list)
        #self.log_text.setPlainText(list)
        #self.log_text.setPlainText(content)
        #print(list)
        #self.log_text.append(self,list)
        #for i in range(list):
        #self.tableWidget.setItem(i,0,QTableWidgetItem(list[i]))
        #self.log_text.append(self,ord_list)
        # for i in range(len(list)):
        #     for j in range(len(list)):

        # self.tableWidget.setColumnWidth(j, 80)  # 设置j列的宽度
        #self.tableWidget.setRowHeight(i, 50)  # 设置i行的高度
        # self.tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直表头
        # self.tableWidget.horizontalHeader().setVisible(False)  # 隐藏水平表头

        print('\n', 'end', '\n++++++++++++++++++++')
Beispiel #4
0
 def __init__(self, log_dir, process_names=[]):
     os.chdir(log_dir)
     if process_names is None:
         process_names = []
     self.process_names = process_names
     for device_dir in self.list_device_dirs():
         logger.info('create report for %s' % device_dir)
         core_num = 1
         try:
             with open(os.path.join(device_dir, 'corenum.txt'), 'r') as f:
                 core_num = int(f.read())
         except:
             pass
         file_names = self.filter_file_names(device_dir)
         logger.debug('%s' % file_names)
         if file_names:
             book_name = '%s-%s.xlsx' % (device_dir, datetime.now().strftime('%Y.%m.%d-%H.%M.%S'))
             excel = Excel(book_name)
             for file_name in file_names:
                 name = file_name.split('.')[0]
                 info = INFO_CONFIG.get(name)(device_dir, file_name, process_names, core_num)
                 for sheet in info.get_sheet_list():
                     logger.info('add sheet %s' % sheet[0])
                     excel.add_sheet(*sheet)
             logger.info('wait to save %s' % book_name)
             excel.save()
Beispiel #5
0
    def on_clicked_pushButton_3(self):
        if self.senderList:
            e = Excel()
            if self.senderList:
                colnum = len(self.senderList)
                for i in range(len(self.senderList)):
                    e.setRangeFormat('sheet1', 1, i + 1, colnum, i + 1, '@')
            if self.senderList:
                for i, row in enumerate(self.senderList):
                    for j, cell in enumerate(row):
                        e.setCell('sheet1', i + 1, j + 1, str(cell))
            desktop = os.path.join(os.path.expanduser("~"), 'Desktop')
            savename = '发件人信息' + time.strftime('%m%d', time.localtime())
            savepath = desktop + '\\' + savename
            fname = QFileDialog.getSaveFileName(self, '保存', savepath, '.xlxs')
            fpath = os.path.abspath(fname[0])
            try:
                e.save(fpath)
            except Exception as e:
                self.showMsg('错误!', '保存时发生错误:\n {}'.format(e.args))
            finally:
                e.close()

        else:
            self.showMsg('错误!', '请先上传表格并完成转换。')
Beispiel #6
0
def main():
    parser = argparse.ArgumentParser(description='XPlan import/export conditions')
    parser.add_argument('-i', '--import-zip', action='store_true', help='Import page.zip and generate excel file.')
    parser.add_argument('-o', '--export-zip', action='store_true', help='Export excel to page.zip')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    if args.import_zip and args.export_zip:
        parser.print_help()
        sys.exit(1)

    if args.import_zip:
        p = XPlan()
        if p.load_zip():
            x = Excel()
            p.extract_objects()
            p.generate_obj_file()
            x.generate_xls_file(p.get_xplan_object())

        logging.info("[Complete]\n\n")

    if args.export_zip:
        p = XPlan()
        x = Excel()
        p.generate_zip_file(x.get_xplan_object())
        logging.info("[Complete]\n\n")
Beispiel #7
0
 def init(self):
     
     self.excel=Excel()
     path='C:/Users/yyw/Desktop/study/환시스/homepluscenter.xlsx'
     self.excel.get_execel(path)
     self.excel.get_sheet('Sheet1')
     self.n =1
     self.i=0
    def test_write_file(self):
        """Archivo de excel generado de manera correcta"""
        xl = Excel()
        data = [["No Cliente", "Nombre"], ["1948393849383", "asdfasdf"],
                ["853939383938293", "asasdfasdfasdf"]]
        xl.write_file("prueba1", "result-val", data)

        self.assertTrue(True)
Beispiel #9
0
    def run(self):
        excel = Excel(self.xls_filename)

        xml = XmlData(self.func_relation_id)
        # xml_data = xml.get_func_xml()
        xml_data = xml.test()

        excel.write_to_xls(xml_data)
    def test_read_data(self):
        """La información es correcta"""
        xl = Excel()
        data = xl.read_file("samplexl.xlsx", "datosm")

        data_expected = [("Nombre", "App", "Apm"), ("X", "T", "G"),
                         ("E", "A", "E")]

        self.assertEqual(data, data_expected)
class TestExcel(unittest.TestCase):

	def setUp(self):
		q = Query()
		fifth_third_transactions = q.get_transactions_by_range('53',5,6)
		self.e = Excel(fifth_third_transactions,PATH)

	def test_grouped_transactions(self):
		self.e.grouped_transactions()
Beispiel #12
0
 def find_item_source_fourth_step_edit_excel(self,path,sheet):
     self.excel=Excel()
     self.excel.get_execel(path)
     self.excel.get_sheet(sheet)
     for i in range(len(self.list_comp)):
         
         self.excel.edit_excel_data(i+1,1,self.list_name[i])
         self.excel.edit_excel_data(i+1,2,self.list_comp[i])
         self.excel.edit_excel_data(i+1,3,self.list_number[i])
     self.excel.save_excel_data()
Beispiel #13
0
 def __init__(self):
     self.item_name=''
     self.category =''
     self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
     self.num_3=0    #num_3
     self.num_2=28
     self.num_1=8
     self.excel=Excel()
     self.three_division=['']
     self.two_division=['']
     self.one_division=['']
Beispiel #14
0
 def init(self):
     self.excel = Excel()
     path = 'C:/Users/yyw/Desktop/study/환시스/homepluscenter.xlsx'
     self.excel.get_execel(path)
     self.excel.get_sheet('Sheet1')
     self.excel1 = Excel()
     path = 'C:/Users/yyw/Desktop/study/환시스/resulthomeplus.xlsx'
     self.excel1.get_execel(path)
     self.excel1.get_sheet('Sheet1')
     self.y = 1
     self.z = []
     self.v = []
     self.map_2 = folium.Map(location=[37.509668, 126.887726], zoom_start=7)
Beispiel #15
0
    def goto_allsheetname(self):
        print('++++++++++++++++++++\n', 'debug', '\n')

        str = "path:" + file_path + '\n'

        excel = Excel(file_path)  # 创建实例化
        print('all sheets')
        list = []
        list = excel.read_all_sheetnames(file_path)
        print('sheet names:', list)
        print('\n', 'end', '\n++++++++++++++++++++')
        str += "all sheet\n" + '; '.join(list)
        self.log_text.setPlainText(str)
Beispiel #16
0
 def init(self):
     self.excel = Excel()
     path = 'C:/Users/yyw/Desktop/study/환시스/emart.xlsx'
     self.excel.get_execel(path)
     self.excel.get_sheet('Sheet1')
     self.n = 3
     self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
     self.driver.get('https://store.emart.com/branch/list.do')
     self.header = {
         'User-Agent':
         'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/76.0.3809.132 Safari/537.36'
     }
     self.i = 405
     self.i1 = 406
Beispiel #17
0
 def main():
     filename = "fatture.xlsx"
     if len(sys.argv) > 1:
         filename = sys.argv[1]
     if not check_file(filename):
         return
     excel = Excel(filename)
     openssl = OpenSSL("data/SanitelCF.cer")
     configurazione = excel.configurazione()
     try:
         while True:
             try:
                 riga = excel.nuova_riga()
             except ValueError as e:
                 print(e)
                 continue
             if not riga:
                 break
             if riga.get("protocollo"):
                 # riga con già il numero di protocollo
                 continue
             mapped = mapping(configurazione, riga, openssl)
             result = send_data(mapped)
             print("%s - %s" % (mapped["numDocumento"], result[1]))
             excel.protocollo(result[1])
     finally:
         excel.save()
Beispiel #18
0
    def file_open(self):

        # open file open dialog
        path, _ = QFileDialog.getOpenFileName(
            self, "Open file", "", "Excel documents (*.xlsx);All files (*.*)")

        if (not path.endswith("xlsx")):
            QMessageBox.about(self, "Error", "Must choose excel file (.xlsx)")
            return
        # process excel file ( excel.py )
        self.xls = Excel(path)

        # Get all the sheet names that hold User stories and Test Cases
        self.comboBoxUS.addItems(self.xls.get_US_names())
Beispiel #19
0
def main():
    base_url = "https://google.com/search?q={}&num={}"
    nums = 50
    # desktop user-agent
    USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36"
    # mobile user-agent
    MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36"

    proxies = {
        "http": "http://127.0.0.1:1081",
        "https": "http://127.0.0.1:1081",
        "socks5": "socks5://127.0.0.1:1081"
    }

    browser = Driver()
    browser.init_dirver()

    excel = Excel(file_name="result.xlsx")

    keywords = [
        "self-clarity scale", "self-clarification scale", "self-esteem scale",
        "自尊量表", "自我概念清晰度量表"
    ]

    results = {}

    for keyword in keywords:
        print("[+]: searching {}".format(keyword))
        keyword = keyword.replace(' ', '+')
        url = base_url.format(keyword, nums)
        browser.get_html_source(url=url)

        soup = BeautifulSoup(browser.html, "html.parser")

        keyword_result = []

        for g in soup.find_all('div', class_='g'):
            anchors = g.find_all('a')
            if anchors:
                link = anchors[0]['href']
                title = g.find('h3').text
                item = {"title": title, "link": link}
                keyword_result.append(item)

            excel.write(sheet_name=keyword, data_array=[title, link])

        results.update({keyword: keyword_result})

        json.dumps(results)
Beispiel #20
0
    def init(self):
        self.excel = Excel()
        path = 'C:/Users/yyw/Desktop/study/환시스/resultlotte.xlsx'
        self.excel.get_execel(path)
        self.excel.get_sheet('Sheet1')
        self.n = 2
        self.m = 2
        self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')

        self.header = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/76.0.3809.132 Safari/537.36'
        }
        self.i = 1
        self.q = 0
Beispiel #21
0
    def init(self, item_url):
        self.excel = Excel()
        path = 'C:/Users/yyw/Desktop/study/환시스/homeplus.xlsx'
        self.excel.get_execel(path)
        self.excel.get_sheet('Sheet1')
        self.n = 3
        self.m = 2
        self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
        self.driver.get(item_url)
        self.header = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/76.0.3809.132 Safari/537.36'
        }
        self.i = 0

        self.window_before = self.driver.window_handles[0]
Beispiel #22
0
    def __init__(self, output: str, query: str = "") -> None:
        self.query: str = query
        self.page: int = 1
        self.parsing: bool = True

        self.excel: Excel = Excel(output)
        self.session: requests.Session = requests.Session()
Beispiel #23
0
    def on_gen_btn_clicked(self):
        if len(self.json) > 0:
            # print(os.path.join(self.targetEdit.text().strip(), "预决算.xls"))
            # if self.check_excel_is_open(os.path.join(self.targetEdit.text().strip().replace("/", "\\"), "预决算.xls")):
            #     QMessageBox.information(self, "提示", '    Excel文件已经打开,请先关闭!    ')
            #     return
            excel_writer = Excel(
                os.path.join(self.targetEdit.text().strip().replace("/", "\\"),
                             "预决算.xls"), self.sheet_name_list, self.json)
            try:
                excel_writer.write_excel()
            except:
                QMessageBox.information(self, "提示", '    写入失败查看是否文件已经打开!    ')
                return

            QMessageBox.information(self, "提示", '    Json信息写入Excel成功!    ')
Beispiel #24
0
def excel():
    """
    Post an excel file and fetch it's configuration
    """
    excel_file = request.files['file']
    sheet = request.values.get('sheet')
    conditional_formatting = False if request.values.get(
        'conditional_formatting') == 'false' else True
    excel = Excel(get_config(),
                  excel_file._file,
                  conditional_formatting=conditional_formatting)
    confluence = Confluence(get_config())
    content = excel.parse(sheet=sheet)
    content['header'] = request.values.get('header')
    content['source'] = confluence.source_from_data(
        content.get('data', {}), header=content.get('header'))
    return json.dumps(content, default=json_serial)
Beispiel #25
0
class Work:
    def __init__(self):
        self.c=Crawl()
        self.e=Excel()

    def thread_it(self,func):
        # 创建线程
        t = threading.Thread(target=func)
        # 守护线程
        t.setDaemon(True)
        # 启动
        t.start()

    def setUp(self):
        #pb.start()
        self.c.setUp()
        #pb.stop()

    def crawl(self):
        var.set('')
        start_row=int(start.get())
        end_row=int(end.get())
        list=self.e.get_title_list(start_row,end_row)#title_list
        print(list,flush=True)
        self.c.crawl(list)
        time.sleep(2)
        start.delete(0,tk.END)
        end.delete(0,tk.END)
        time.sleep(1)
        start.insert(0,end_row+1)
        end.insert(0,end_row+4)
        num=end_row-start_row+1
        var.set('请输入'+str(num)+'个结果 ')
        #num_list=c.insert() 
        #self.e.write_num(num_list)

    def insert(self):
        num=e.get()
        num_list=[int(i) for i in re.split('[,,]',num)]
        print(num_list,flush=True)
        self.e.write_num(num_list)
        e.delete(0,tk.END)
        var.set('数据已导入 ')

    def tearDown(self):
       self.c.tearDown()
Beispiel #26
0
    def init(self):
        self.excel = Excel()
        path = 'C:/Users/yyw/Desktop/study/환시스/homepluscenter.xlsx'
        self.excel.get_execel(path)
        self.excel.get_sheet('Sheet1')

        self.excel1 = Excel()
        path = 'C:/Users/yyw/Desktop/study/환시스/homeplus.xlsx'
        self.excel1.get_execel(path)
        self.excel1.get_sheet('Sheet1')

        self.y = 1
        self.y1 = 1
        self.df = pd.DataFrame(columns=('latitude', 'longitude'))
        self.df1 = pd.DataFrame(columns=('latitude', 'longitude'))
        self.n = 0
        self.n1 = 0
Beispiel #27
0
def main():
    for path in get_xls_files(setting.work_dir()):
        excel = Excel(setting.work_dir() + path)
        data = get_data4json(excel)

        split_pre = path.find(SUFFIX) - 1
        name = path[:split_pre] + ".json"

        write_json(name, data)
Beispiel #28
0
 def init(self):
     self.excel=Excel()
     path='C:/Users/yyw/Desktop/study/환시스/homepluscenter.xlsx'
     self.excel.get_execel(path)
     self.excel.get_sheet('Sheet1')
     self.excel2=Excel()
     path='C:/Users/yyw/Desktop/study/환시스/emartcenter.xlsx'
     self.excel2.get_execel(path)
     self.excel2.get_sheet('Sheet1')
     self.n =1
     self.m=2
     self.driver = webdriver.Chrome('C:/chromedriver/chromedriver.exe')
     self.driver.get('https://map.naver.com/')
     self.header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/76.0.3809.132 Safari/537.36'}
     self.i=0
     self.q=0
     self.y2=5
     self.y3=0
Beispiel #29
0
    def output_to_excel(self):
        """Output the full event list to an excel file.

        Args:
            None

        Returns:
            None 
        """
        Excel(self).save()
Beispiel #30
0
def execution(type, count, item_type):
    sm = ScreenManager()
    rp = RechercheProcess()
    r = Item()

    sm.set_focus_by_window_name("Greenlamp")
    rp.search_multiple_item(type, count)

    items = r.generate_item_list(type)
    Excel(items, item_type)
Beispiel #31
0
def excelGen():
    os.remove('data_dictionary/profiles.xlsx')
    #../../profiles.xlsx
    wb = Workbook()
    ws = wb.active
    ws['A1'] = ''
    wb.save('data_dictionary/profiles.xlsx')
    #../../profiles.xlsx
    for profile in ['community', 'collection', 'generic', 'thesis', 'oai_pmh', 'oai_etdms']:
    	Excel(profile)
Beispiel #32
0
    def output_to_excel(self):
        """Output the full event list to an Excel file.

        Author: KomorebiL

        Args:
            None

        Returns:
            None 
        """
        Excel(self).save()
Beispiel #33
0
def main():
    browser = Driver()
    browser.init_dirver(headless=False)
    excel = Excel(file_name="result.xlsx")
    tb = Taobao(browser)

    keywords = ["Pico G2 4KS"]
    excel_title = ["名称", "价格", "月销量", "店铺", "地址", "商品链接", "店铺链接"]

    results = {}

    for keyword in keywords:
        print("[+]: searching {} ...".format(keyword))
        keyword = keyword.replace(' ', '+')

        excel.write(sheet_name=keyword, data_array=excel_title)

        tb.login()
        tb.search(keyword)
        results = tb.get_items()

        for item in results:
            item_data = [
                item.name, item.price, item.sales, item.shop, item.location,
                item.links, item.shop_links
            ]
            excel.write(sheet_name=keyword, data_array=item_data)
    def onButton_data(self, event):
        """
        This method is fired when its corresponding button is pressed
        """
        openDirDialog = wx.DirDialog(self.panel1, 'Choose input directory', '.', wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        #
        if openDirDialog.ShowModal() != wx.ID_CANCEL:
            # ----------------------------------------
            # Get all data files
            # ----------------------------------------
            patients = {}
            for filename in glob.glob(openDirDialog.GetPath() + os.sep + '*.txt'):
                file_content = AminoacidAnalyzes_file(filename)
                if file_content.patient not in patients:
                    patients[file_content.patient] = Patient()
                patients[file_content.patient].add_data(file_content)
            #
            # ----------------------------------------
            # Create result folder
            # ----------------------------------------
            folder = ''.join((openDirDialog.GetPath(), os.sep, '..', os.sep, 'result', os.sep))
            if not os.path.isdir(folder):
                os.makedirs(folder)
            # ----------------------------------------
            # Go through each patient data and create an excel file for each
            # ----------------------------------------
            uptakes = {}
            for patient in patients:
                print patient
                patients[patient].calculate_average()
                # ----------------------------------------
                # Create Excel file
                # ----------------------------------------
                excelfile = Excel()
                # ----------------------------------------
                # Raw data
                # ----------------------------------------
                excelfile.add_sheet('raw data', patients[patient].raw_data()[1])
                # ----------------------------------------
                # Concentration
                # ----------------------------------------
                excelfile.add_sheet('concentration', patients[patient].raw_data()[0])
                # ----------------------------------------
                # Mean + Std
                # ----------------------------------------
                excelfile.add_sheet('mean', patients[patient].mean_std())
                # ----------------------------------------
                # Normalized to aminoacid
                # ----------------------------------------
                for i in xrange(len(patients[patient].aa)):
                    #
                    new = np.array(patients[patient].normalized(-1, i))
                    if i == 0:
                        a = new
                    else:
                        a = np.concatenate((a, new), axis = 1)
                #
                excelfile.add_sheet('normalized', a)
                # ----------------------------------------
                # Uptake
                # ----------------------------------------
                excelfile.add_sheet('uptake', patients[patient].normalized(0, -1))
                # ----------------------------------------
                # Uptake normalized
                # ----------------------------------------
                for i in xrange(len(patients[patient].aa)):
                    new = np.array(patients[patient].normalized(0, i))
                    if i == 0:
                        a = new
                    else:
                        a = np.concatenate((a, new), axis = 1)
                #
                excelfile.add_sheet('uptake normalized', a)
                # ----------------------------------------
                # Save Excel datafile
                # ----------------------------------------
                excelfile.save_excel_file(folder + patient + '.xls')
                # ----------------------------------------
                # Uptake is Arg
                # ----------------------------------------
                uptakes[patient] = patients[patient].uptake(7)
            # ----------------------------------------
            # Create a file with all results
            # ----------------------------------------
            excelfile = Excel()
            groups = list(set([key.split('-')[0] for key in uptakes.keys()]))
            groups.sort()
            patient_data = [['patient'] + patients[uptakes.keys()[0]].samples]
            for group in groups:
                keys = []
                group_data = []
                for key in uptakes.keys():
                    if group in key:
                        keys.append(key)
                        group_data.append(uptakes[key])
                group_data = np.array(group_data)
                mean = group_data.mean(axis = 0)
                std = group_data.std(axis = 0)

                for key in keys:
                    patient_data.append([key] + uptakes[key])
                patient_data.append(['' for _ in xrange(len(mean)+1)])
                patient_data.append(['Mean'] + list(mean))
                patient_data.append(['Std'] + list(std))
                patient_data.append(['' for _ in xrange(len(mean)+1)])
                patient_data.append(['' for _ in xrange(len(mean)+1)])

            patient_data = np.array(patient_data)
            excelfile.add_sheet('patient_data', patient_data.T)
            excelfile.save_excel_file(folder + 'patients.xls')
            # ----------------------------------------
            # Finish
            # ----------------------------------------
            self.button_data.Label = 'Saved!'
        #
        openDirDialog.Destroy()
        #
        return None
Beispiel #35
0
    def dlinks_from_excel(self, xls_file):
        """Read links between variables from an Excel file.

        The Excel file should have the following format:

        ======= ====== ======= ======= ======= ======= ======= ======= =======
        .       col j  col j+1 col j+2 col j+3 col j+4 col j+5 col j+6 col j+7
        ======= ====== ======= ======= ======= ======= ======= ======= =======
        row i   DLINK
        row i+1
        row i+2 dvar   c0      c       ivar1   c1      ivar2   c2      ...
        row i+3 LP.1.1 0.      1.      LS.1.1  0.4     LS.1.2  0.6     ...
        ======= ====== ======= ======= ======= ======= ======= ======= =======

        where the relative position between the cell with `DLINK` and the
        others must be held.

        Parameters
        ----------
        xls_file : str
            The full path of the Excel file.

        """
        from excel import Excel

        ex = Excel(xls_file)
        found = False
        print('Reading Excel File %s...' % xls_file)
        for row in range(1, 101):
            for col in range(1, 256):
                rvalue = ex.get_cell(1, row, col)
                if 'DLINK' == rvalue:
                    found = True
                    break
            if found:
                break
        dlinks = {}
        count = -1
        irow = row + 3
        for row in range(irow, 65536):
            dvar_code = ex.get_cell(1, row, col)
            if dvar_code is None:
                break
            print('    creating DLINK for variable: %s' % dvar_code)
            c0 = ex.get_cell(1, row, col + 1)
            c = ex.get_cell(1, row, col + 2)
            ivar_code_1 = ex.get_cell(1, row, col + 3)
            c_1 = ex.get_cell(1, row, col + 4)
            ivar_code_2 = ex.get_cell(1, row, col + 5)
            c_2 = ex.get_cell(1, row, col + 6)
            ivar_code_3 = ex.get_cell(1, row, col + 7)
            c_3 = ex.get_cell(1, row, col + 8)

            dvar = self.dvar_codes[dvar_code]
            ivar_1 = self.dvar_codes[ivar_code_1]

            try:
                dvi_ci = [ivar_1.id, float(c_1)]
            except:
                dvi_ci = [ivar_1.id, str(c_1)]

            if ivar_code_2.__class__.__name__ <> 'NoneType':
                ivar_2 = self.dvar_codes[ivar_code_2]
                dvi_ci = dvi_ci + [ivar_2.id, float(c_2)]

            if ivar_code_3.__class__.__name__ <> 'NoneType':
                ivar_3 = self.dvar_codes[ivar_code_3]
                dvi_ci = dvi_ci + [ivar_3.id, float(c_3)]

            count += 1
            self.dlinks[count] = DLINK(dvar.id, dvi_ci, c0=c0, cmult=c)

        ex.close()
Beispiel #36
0
    def nodal_displ_from_excel(self, xls_file):
        """Create nodal displacement constraints based on an Excel file.

        This function reads the xls file with nodal displacement constraints
        and returns a dictionary with the format::

            nd = {load_case_id1 : {grid_1 : {output : [minvalue, maxvalue],
                                   grid_2 :  output : [minvalue, maxvalue],
                                   grid_3 :  output : [minvalue, maxvalue]}}
                  load_case_id2 : {grid_1 : {output : [minvalue, maxvalue],
                                   grid_3 :  outout : [minvalue, maxvalue]}}}

        where `minvalue` and `maxvalue` are the minimum and maximum
        displacement values.

        Parameters
        ----------
        xls_file : str
            The full path to the Excel file.

        Returns
        -------
        output : str
            A string with one of the values:

            - `'Translation X'`
            - `'Translation Y'`
            - `'Translation Z'`
            - `'Rotation X'`
            - `'Rotation Y'`
            - `'Rotation Z'`
            - `'Translation Total'`
            - `'Absolute X'`
            - `'Absolute Y'`
            - `'Absolute Z'`

        """
        from excel import Excel

        if not xls_file:
            return None

        ex = Excel(xls_file)
        found = False
        for row in range(1, 100):
            for col in range(1, 23):
                refvalue = str(ex.get_cell(1, row, col))
                if refvalue.find('DISPLACEMENT CONSTRAINTS') > -1:
                    found = True
                    break
            if found:
                break
        nd = {}
        irow = row + 2
        #TODO this try/except block is mainly to avoid Excel from being
        #     a defunct
        try:
            for row in range(irow, 65536):
                load_id = ex.get_cell(1, row, col)
                if load_id.__class__.__name__ == 'NoneType':
                    break
                #
                load_id = int(load_id)
                node_id = ex.get_cell(1, row, col + 1)
                node_id = int(node_id)
                output = ex.get_cell(1, row, col + 2)
                output = str(output)
                minvalue = ex.get_cell(1, row, col + 3)
                minvalue = float(minvalue)
                maxvalue = ex.get_cell(1, row, col + 4)
                maxvalue = float(maxvalue)
                if not load_id in nd.keys():
                    nd[load_id] = {}
                if not node_id in nd[load_id].keys():
                    nd[load_id][node_id] = {}
                nd[load_id][node_id][output] = [minvalue, maxvalue]
            ex.close()
            self.nodal_displ = nd

        except:
            ex.close()
            print('nodal_displ_from_excel() failed!')

            return None

        for load_id in nd.keys():
            for node_id in nd[load_id].keys():
                for con_name in nd[load_id][node_id].keys():
                    con_minvalue = nd[load_id][node_id][con_name][0]
                    con_maxvalue = nd[load_id][node_id][con_name][1]

                    for k, v in OUTC['DISP'].iteritems():
                        if v.find(con_name) > -1:
                            code = k
                            break

                    if code == 7:
                        #DRESP1 x
                        labelx = 'x' + str(node_id)
                        dresp1 = DRESP1(labelx, 'DISP', '', '', 1, [node_id])
                        self.dresps[dresp1.id] = dresp1
                        dresp1xid = dresp1.id

                        #DRESP1 y
                        labely = 'y' + str(node_id)
                        dresp1 = DRESP1(labely, 'DISP', '', '', 2, [node_id])
                        self.dresps[dresp1.id] = dresp1
                        dresp1yid = dresp1.id

                        #DRESP1 z
                        labelz = 'z' + str(node_id)
                        dresp1 = DRESP1(labelz, 'DISP', '', '', 3, [node_id])
                        self.dresps[dresp1.id] = dresp1
                        dresp1zid = dresp1.id

                        #DEQATN
                        eq = ('T(%s,%s,%s)=SQRT(%s**2+%s**2+%s**2)' %
                        (labelx, labely, labelz, labelx, labely, labelz))
                        deqatn = DEQATN(eq)
                        self.deqatns[deqatn.id] = deqatn

                        #DRESP23
                        label = 'r' + str(node_id)
                        dresp23 =  DRESP23(label, deqatn.id)
                        dresp23.add_dresp1(dresp1xid)
                        dresp23.add_dresp1(dresp1yid)
                        dresp23.add_dresp1(dresp1zid)
                        self.dresps[dresp23.id] = dresp23

                        #DCONS
                        stress_type = 'positive'
                        lid_lb_ub = [str(load_id), con_minvalue, con_maxvalue]
                        self.dcons[dresp23.id] = DCONS(dresp23.id, lid_lb_ub,
                                                       stress_type)
                    elif (code == 8 or code == 9 or code == 10):
                        #DRESP1
                        label = 'a' + str(node_id)
                        dresp1 = DRESP1(label, 'DISP', '', '', code, [node_id])
                        self.dresps[dresp1.id] = dresp1

                        #DEQATN
                        eq = 'D(%s)=ABS(%s)' % (label, label)
                        deqatn = DEQATN(eq)
                        self.deqatns[deqatn.id] = deqatn

                        #DRESP23
                        label = 'r' + str(node_id)
                        dresp23 = DRESP23(label, deqatn.id)
                        dresp23.add_dresp1(dresp23.id)
                        self.dresps[dresp23.id] = dresp23

                        #DCONS
                        stress_type = 'positive'
                        lid_lb_ub = [str(load_id), con_minvalue, con_maxvalue]
                        self.dcons[dresp23.id] = DCONS(dresp23.id, lid_lb_ub,
                                                       stress_type)
                    else:
                        #DRESP1
                        label = 'r' + str(node_id)
                        dresp1 = DRESP1(label, 'DISP', '', '', code, [node_id])
                        self.dresps[dresp1.id] = dresp1

                        #DCONS
                        stress_type = 'both'
                        lid_lb_ub = [str(load_id), con_minvalue, con_maxvalue]
                        self.dcons[dresp1.id] = DCONS(dresp1.id, lid_lb_ub,
                                                      stress_type)
	def setUp(self):
		q = Query()
		fifth_third_transactions = q.get_transactions_by_range('53',5,6)
		self.e = Excel(fifth_third_transactions,PATH)
Beispiel #38
0
# -*- coding: utf-8 -*-
# authors 13077/13130
# data: 05 de outubro de 2014
#

from excel import Excel
from db import Database

# x = Excel("../Data/IPC_Portugal_1977_2013.xls")
x = Excel("C:/Users/Diogo/Dropbox/ESTIG/2/S1/LP/LP-1415/IPC_Portugal_1977_2013.xls")
#x.readFile()
#lista = x.lista

x.read_data()
lista2 = x.lista2

d = Database(lista2)
d.drop_table()
d.create_table()

d.insert_data()

d.test()


# test test tes tes testest se es test es te te s