Работа с excel lua

More complex code example for lua working with excel:

require "luacom"

excel = luacom.CreateObject("Excel.Application")

local book  = excel.Workbooks:Add()
local sheet = book.Worksheets(1)

excel.Visible = true

for row=1, 30 do
  for col=1, 30 do
    sheet.Cells(row, col).Value2 = math.floor(math.random() * 100)
  end
end


local range = sheet:Range("A1")

for row=1, 30 do
  for col=1, 30 do
    local v = sheet.Cells(row, col).Value2

    if v > 50 then
        local cell = range:Offset(row-1, col-1)

        cell:Select()
        excel.Selection.Interior.Color = 65535
    end
  end
end

excel.DisplayAlerts = false
excel:Quit()
excel = nil 

Another example, could add a graph chart.

require "luacom"

excel = luacom.CreateObject("Excel.Application")

local book  = excel.Workbooks:Add()
local sheet = book.Worksheets(1)

excel.Visible = true

for row=1, 30 do
  sheet.Cells(row, 1).Value2 = math.floor(math.random() * 100)
end

local chart = excel.Charts:Add()
chart.ChartType = 4 — xlLine

local range = sheet:Range("A1:A30")
chart:SetSourceData(range) 

Introduction

The module xls allows high performance read and write access to .xls files.

Example

    require 'xls'

    local doc = xls.BasicExcel()

xls Reference

workbook = xls.Workbook([filename])

Creates or opens a Workbook object. Returns a Workbook object.

  • filename is the optional name of the .xls file to open. If no filename is given, an empty Workbook is created.

Workbook Reference

workbook:New(sheets [ = 3])

Creates a new Excel workbook with a given number of worksheets.

  • sheets is the number of worksheets to create within the workbook. The minimum is 1. The default is 3.

loaded = workbook:Load(filename)

Loads an Excel workbook from a file.

Returns true if successful, false otherwise.

  • filename is the path to the .xls file to open.

saved = workbook:Save()

Saves current Excel workbook to the opened file.

Returns true if successful, false if unsuccessful.

saved = workbook:SaveAs(filename)

Loads an Excel workbook from a file.

Returns true if successful, false otherwise.

  • filename is the path to the .xls file to save. filename may be a regular string or an xls.wchar.

workbook:Close()

Closes the current Excel workbook.

totalWorksheets = workbook:GetTotalWorksheets()

Returns the total number of Excel worksheets in the current Excel workbook.

worksheet = workbook:GetWorksheet(sheetIndex | name)

Returns an object representing the Excel worksheet specified by sheetIndex or name. If no worksheet is found with the given sheetIndex or name, then GetWorksheet returns nil.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the sheet to retrieve.
  • name is either a string or an xls.wchar representing the sheet name to retrieve.

worksheet = workbook:AddWorksheet([sheetIndex] | [name [, sheetIndex]])

Adds a new worksheet to the workbook. If no sheetIndex or name is specified, a new worksheet is added to the last position.

Returns an Excel worksheet specified by sheetIndex or name.

  • sheetIndex is an index in the range of -1 <= sheetIndex < GetTotalWorksheets(). If -1 is specified, the new worksheet is added to the last position. The name given to the new worksheet is SheetX, where X is a number which starts from 1.
  • name is either a string or an xls.wchar that will become the name of the worksheet being added.

deleted = workbook:DeleteWorksheet(sheetIndex | name)

Deletes the specified Excel worksheet from the workbook.

Returns true if the worksheet was deleted, false otherwise.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the worksheet to delete.
  • name is either a string or an xls.wchar representing the sheet name to delete.

ansiSheetName = workbook:GetAnsiSheetName(sheetIndex)

If possible, returns the ANSI name of the sheet. Otherwise, returns nil if the name is Unicode.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the worksheet to delete.

unicodeSheetName = workbook:GetUnicodeSheetName(sheetIndex)

If possible, returns the Unicode name of the sheet formatted as an xls.wchar. Otherwise, returns nil if the name is ANSI.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the worksheet to delete.

sheetName = workbook:GetSheetName(sheetIndex)

Returns either the ANSI name of the sheet or the Unicode name of the sheet as an xls.wchar.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the worksheet to delete.

renamed = workbook:RenameWorksheet(sheetIndex | from, to)

Renames an Excel worksheet at sheetIndex or from to the name specified by to.

Returns true if the operation succeeded, false otherwise.

  • sheetIndex is an index in the range of 0 <= sheetIndex < GetTotalWorksheets() representing the worksheet to delete.
  • from is either a string or xls.wchar name of the worksheet to rename.
  • to is either a string or xls.wchar name, where the type must match that of from if from is specified, of the worksheet to rename.

Worksheet Reference

ansiSheetName = worksheet:GetAnsiSheetName()

If possible, returns the ANSI name of the sheet. Otherwise, returns nil if the name is Unicode.

unicodeSheetName = worksheet:GetUnicodeSheetName()

If possible, returns the Unicode name of the sheet formatted as an xls.wchar. Otherwise, returns nil if the name is ANSI.

sheetName = worksheet:GetSheetName(sheetIndex)

Returns either the ANSI name of the sheet or the Unicode name of the sheet as an xls.wchar.

renamed = worksheet:Rename(to)

Renames the Excel worksheet to the name specified by to.

Returns true if the operation succeeded, false otherwise.

  • to is either a string or xls.wchar name, where the type must match that of from if from is specified, of the worksheet to rename.

totalRows = worksheet:GetTotalRows()

Returns the total number of rows in the Excel worksheet.

totalColumns = worksheet:GetTotalCols()

Returns the total number of columns in the Excel worksheet.

cell = worksheet:Cell(row, col)

Retrieves the contents of a cell from the Excel worksheet.

Returns the cell if the operation succeeded, nil if either the row or column are not in range.

  • row is a value from 0 to 65535, representing the row in the Excel worksheet to retrieve.
  • col is a value from 0 to 255, representing the column in the Excel worksheet to retrieve.

erased = worksheet:EraseCell(row, col)

Erases the contents of a cell from the Excel worksheet.

Returns true if successful, false if either the row or column are not in range.

  • row is a value from 0 to 65535, representing a row in the Excel worksheet.
  • col is a value from 0 to 255, representing a column in the Excel worksheet.

worksheet:SetColWidth(col)

Sets the width of the given column in the Excel worksheet.

  • col is a value from 0 to 255, representing the column in the Excel worksheet to retrieve.

columnWidth = worksheet:GetColWidth(col)

Returns the width of the column in the Excel worksheet.

  • col is a value from 0 to 255, representing a column in the Excel worksheet.

worksheet:MergeCells(row, col, rowRange, colRange)

Merges the cell specified by row and col into a single cell consisting in height of rowRange rows and colRange columns.

  • row is a value from 0 to 65535, representing a row in the Excel worksheet.
  • col is a value from 0 to 255, representing a column in the Excel worksheet.
  • rowRange is a value from 1 to (65535 — row — 1).
  • colRange is a value from 1 to (255 — row — 1).

Cell Reference

cellType = cell:Type()

Returns one of the following as the type of this Excel cell.

  • cell.UNDEFINED
  • cell.INT
  • cell.DOUBLE
  • cell.STRING
  • cell.WSTRING
  • cell.FORMULA

cellContent = cell:Get()

If the type of the cell is cell.INT or cell.DOUBLE, the integer or double content of the cell is returned as a Lua number. If the type of the cell is cell.STRING, the ANSI string content of the cell is returned as a Lua string. If the type of the cell is cell.WSTRING, the Unicode string content of the cell are returned as an xls.wchar. Otherwise, nil is returned.

cellContent = cell:GetInteger()

If the type of the cell is cell.INT, the integer content of the cell is returned as a Lua number. Otherwise, nil is returned.

cellContent = cell:GetDouble()

If the type of the cell is cell.DOUBLE, the double content of the cell is returned as a Lua number. Otherwise, nil is returned.

cellContent = cell:GetString()

If the type of the cell is cell.STRING, the ANSI string content of the cell is returned as a Lua string. Otherwise, nil is returned.

cellContent = cell:GetWString()

If the type of the cell is cell.WSTRING, the Unicode string content of the cell is returned as an xls.wchar. Otherwise, nil is returned.

cell:Set(value)

Sets the content of the cell to value.

  • value represents the new content of the cell.
    ** If value is a number, the number is assumed to be a double, and the cell type becomes cell.DOUBLE.
    ** If value is a string, the cell type becomes cell.STRING.
    ** If value is an xls.wchar, the cell type becomes cell.WSTRING.

cell:SetInteger(value)

Sets the content of the cell to value.

  • value represents the new integer content of the cell. The cell type becomes cell.INT.

cell:SetRKValue(value)

To be documented.

cell:SetString(value)

Sets the content of the cell to value.

  • value represents the new ANSI string content of the cell. The cell type becomes cell.STRING.

cell:SetWString(value)

Sets the content of the cell to value.

  • value represents the new Unicode string content of the cell. The cell type becomes cell.WSTRING.

cell:SetFormula(value)

NOT IMPLEMENTED.

cell:GetXFormatIdx()

To be documented.

cell:SetXFormatIdx(value)

To be documented.

cell:SetFormat(value)

To be documented.

cell:EraseContents()

Erase the content of the current Excel cell. The cell type becomes cell.UNDEFINED.

numberOfMergedRows = cell:GetMergedRows()

Return the number of merged rows in the current Excel cell.

numberOfMergedColumns = cell:GetMergedColumns()

Return the number of merged columns in the current Excel cell.

cell:SetMergedRows(mergedRows)

Sets the number of merged rows in the current Excel cell.

cell:SetMergedColumns(mergedColumns)

Sets the number of merged columns in the current Excel cell.


CellFormat Reference


ExcelFont Reference

newFont = xls.Font()

Creates or opens a Workbook object. Returns a Workbook object.

  • filename is the optional name of the .xls file to open. If no filename is given, an empty Workbook is created.

Tutorial 1: Create a simple XLSX file

Let’s start by creating a simple spreadsheet using Lua and the xlsxwriter
module.

Say that we have some data on monthly outgoings that we want to convert into an
Excel XLSX file:

expenses = {
  {"Rent", 1000},
  {"Gas",   100},
  {"Food",  300},
  {"Gym",    50},
}

To do that we can start with a small program like the following:

local Workbook = require "xlsxwriter.workbook"


-- Create a workbook and add a worksheet.
local workbook  = Workbook:new("Expensese01.xlsx")
local worksheet = workbook:add_worksheet()

-- Some data we want to write to the worksheet.
local expenses = {
  {"Rent", 1000},
  {"Gas",   100},
  {"Food",  300},
  {"Gym",    50},
}

-- Start from the first cell. Rows and columns are zero indexed.
local row = 0
local col = 0

-- Iterate over the data and write it out element by element.
for _, expense in ipairs(expenses) do
  local item, cost = unpack(expense)
  worksheet:write(row, col,     item)
  worksheet:write(row, col + 1, cost)
  row = row + 1
end

-- Write a total using a formula.
worksheet:write(row, 0, "Total")
worksheet:write(row, 1, "=SUM(B1:B4)")

workbook:close()

If we run this program we should get a spreadsheet that looks like this:

_images/tutorial01.png

This is a simple example but the steps involved are representative of all
programs that use xlsxwriter, so let’s break it down into separate parts.

The first step is to import the module:

local Workbook = require "xlsxwriter.workbook"

The next step is to create a new workbook object using the Workbook:new()
constructor.

Workbook:new() takes one, non-optional, argument which is the filename that we want to create:

local workbook = Workbook:new("Expensese01.xlsx")

The workbook object is then used to add a new worksheet via the
add_worksheet() method:

local worksheet = workbook:add_worksheet()

By default worksheet names in the spreadsheet will be Sheet1, Sheet2 etc.,
but we can also specify a name:

worksheet1 = workbook:add_worksheet()        -- Defaults to Sheet1.
worksheet2 = workbook:add_worksheet("Data")  -- Data.
worksheet3 = workbook:add_worksheet()        -- Defaults to Sheet3.

We can then use the worksheet object to write data via the write()
method:

worksheet:write(row, col, some_data)

Note

Throughout the xlsxwriter API rows and columns are zero indexed. Thus,
the first cell in a worksheet, A1, is (0, 0).

So in our example we iterate over our data and write it out as follows:

-- Iterate over the data and write it out element by element.
for _, expense in ipairs(expenses) do
  local item, cost = unpack(expense)
  worksheet:write(row, col,     item)
  worksheet:write(row, col + 1, cost)
  row = row + 1
end

We then add a formula to calculate the total of the items in the second column:

worksheet:write(row, 1, "=SUM(B1:B4)")

Finally, we close the Excel file via the close() method:

And that’s it. We now have a file that can be read by Excel and other
spreadsheet applications.

In the next sections we will see how we can use the xlsxwriter module to add
formatting and other Excel features.

csvФайл CSV-формата это обычный текстовый файл, с которым Excel и аналогичные программы могут работать как с таблицей. Каждая строка таблицы в этом файле записывается как новая строка со знаком переноса в конце, а значения полей разделены между собой каким-то символом, чаще «;». В самой первой строке такого файла можно (не обязательно) указать названия столбцов, так же через «;».

Ниже приведен пример создания такого файла и записи в него данных о совершенных сделках средствами QLua(Lua):

Скрипт создает файл следующего вида:
Таблица
Если у Вас появились какие-то вопросы, задайте их в комментариях под статьей !!!

Содержание

  1. Name already in use
  2. lua-xlsx / doc / us / index.md
  3. QUIKBOT . EVOLUTION …
  4. Свежие записи
  5. Архивы
  6. Добавить комментарий Отменить ответ
  7. Из QLua (Lua) в Excel (CSV): 109 комментариев
  8. LUA: How can extract specific values from a xls or csv file and save them as variables?
  9. 2 Answers 2
  10. В помощь QLUA-водам. Функция чтения CSV файла.
  11. local col = 1 local pat = «(.*)» local A=<>;local B=<>;local C=<>;local D=<>;local E=<>; local F=<>;local G=<>;local H=<>;local I=<>;local J=<>; local K=<>;local L=<>;local M=<>;local N=<>;local O=<>; local P=<>;local Q=<>;local R=<>;local S=<>;local T=<>; local file, err = io.open(filename,«r») if err

Name already in use

lua-xlsx / doc / us / index.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

The module xlsx allows read and write access to .xlsx files.

Creates or opens a Workbook object. Returns a Workbook object.

  • filename is the name of the .xlsx file to open.

Returns the total number of Excel worksheets in the current Excel workbook.

worksheet = workbook[sheetIndex | name]

Returns an object representing the Excel worksheet specified by sheetIndex or name . If no worksheet is found with the given sheetIndex or name , then nil is returned.

  • sheetIndex is an index in the range of 1 sheetIndex GetTotalWorksheets representing the sheet to retrieve.
  • name is a string representing the sheet name to retrieve.

Closes the current Excel workbook.

Returns the total number of Excel worksheets in the current Excel workbook.

worksheet = workbook:GetWorksheet(sheetIndex | name)

Returns an object representing the Excel worksheet specified by sheetIndex or name . If no worksheet is found with the given sheetIndex or name , then GetWorksheet returns nil .

  • sheetIndex is an index in the range of 0 sheetIndex GetTotalWorksheets() representing the sheet to retrieve.
  • name is either a string or an xls.wchar representing the sheet name to retrieve.

Returns either the name of the sheet.

  • sheetIndex is an index in the range of 1 sheetIndex GetTotalWorksheets() representing the worksheet to delete.

Returns the name of the sheet.

Returns the total number of rows in the Excel worksheet.

Returns the total number of columns in the Excel worksheet.

cell = worksheet:Cell(row, col)

Retrieves the contents of a cell from the Excel worksheet.

Returns the cell if the operation succeeded, nil if either the row or column are not in range.

  • row is a value from 0 to 65535, representing the row in the Excel worksheet to retrieve.
  • col is a value from 0 to 255, representing the column in the Excel worksheet to retrieve.

Retrieves the contents of a cell from the Excel worksheet.

Returns the cell if the operation succeeded, nil if either the row or column are not in range.

  • COLROW is a column and row in Excel format, such as A4 or BD12.

Returns one of the following as the type of this Excel cell.

Источник

QUIKBOT . EVOLUTION …

Свежие записи

Архивы

  • Al к записи Получение данных из таблиц QUIK в QLua(Lua)
  • w0xxmy к записи Циклы FOR, WHILE, REPEAT в QLua (lua)
  • Vasily к записи Из QLua (Lua) в Excel (CSV)
  • Vasily к записи Из QLua (Lua) в Excel (CSV)
  • mikeorbita к записи Вопрос-ответ
  • mikeorbita к записи Вопрос-ответ
  • denismos к записи Пример скрипта QLua (Lua), выполняющего торговые операции в терминале QUIK
  • Константин к записи Робот Виртуал
  • Dimm к записи Робот Виртуал
  • Dimm к записи Робот Виртуал

Файл CSV-формата это обычный текстовый файл, с которым Excel и аналогичные программы могут работать как с таблицей. Каждая строка таблицы в этом файле записывается как новая строка со знаком переноса в конце, а значения полей разделены между собой каким-то символом, чаще «;». В самой первой строке такого файла можно (не обязательно) указать названия столбцов, так же через «;».

Ниже приведен пример создания такого файла и записи в него данных о совершенных сделках средствами QLua(Lua):

Скрипт создает файл следующего вида:

Если у Вас появились какие-то вопросы, задайте их в комментариях под статьей .

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Из QLua (Lua) в Excel (CSV): 109 комментариев

ДОбрый день! Я взяла ваш скрипт и исопльзую его в своем роботе, но есть сложность: у меня все роботы пишут каждую сделку, не свою, а каждую, при этом как автора сделки ставят именно себя. Как это можно обойти?
Код могу выслать

Здравствуйте, поставьте фильтр по № сделки.
А лучше, при выставлении заявки, делать ее описание (поле brokerref), тогда достаточно 1-го робота (переделать пример выше), который будет писать сделки в разные файлы с именем файла содержащим текст из поля brokerref.

Я правильно понимаю, что название можно указывать в поле комментарии ? Для акций у меня такой фокус не сработал, а для фьючей жду первую сделку. Это, конечно, решило бы вопрос.

Здравствуйте. Поле комментарий составное 20 символов, включая разделитель. Для акций: код_клиента//комментарий. Для срочного рынка просто комментарий.

Спасибо огромное! Очень выручили:)

Да, сделки можно писать и в один файл, просто добавить поле комментарий, а потом фильтровать в экселе.

Приветствую Вас уважаемые создатели ресурса. Прежде всего хочу поблагодарить Вас за ваше невероятное терпение и «веру в человечество» (стремление и желание обучать чайников типа меня).
Я попробовал использовать приведённый выше пример скрипта «ИЗ QLUA (LUA) В EXCEL (CSV)» на срочном рынке. Фьючерс сбер.
Идёт запись только первой половины сделки (покупка для лонга и продажа для шорта) да и та не вся. Лонг 1 лот. Шорт — 5 лотов был разбит на 2-2-1 (за одину продажу, но лоты разных покупателей). Записано было только 2 лота.
Вопрос: возможно ли, что эта ошибка связана со старой версией квика 7.29.0.40? Только не ржите надо мной )))

Немного покопавшись, я обнаружил
— при экспорте из таблицы сделок через ДДЕ-сервер, номера сделок в эксель сбрасываются с округлением до 10 000 (естественно, что они воспринимаются как один номер), т.е рубится 5 знаков справа.
— экспортный файл сохраняемый на диск скриптом вообще выдает формат типа «1.9534635126301e+018» они различаются по номеру заявки. Номер Сделок же всех — «на одно лицо».
Стало очевидно, что проблема возникает из-за невозможности правильно считать 19 значный номер старым софтом.
Приношу извинения за флуд, т.к. не хотелось отвлекать достопочтенную публику по пустякам.

Здравствуйте, подскажите почему может не работать данный скрипт с файлом формата .XLSX ? В коде везде поменял формат файла.

Здравствуйте, потому что CSV — это обычный текстовый файл, который понимает программа Excel а .XLSX это файл Excel, с ним как с обычным текстовым невозможно работать.

Привет. Вопрос. Есть csv файл с 3 строками.
1я — «Первая»
2я — «Вторая»
3я — «Третья»
Возможно ли перезаписать какую либо строку. Например вторую — «Получилось Ура». Получить результат:
1я — «Первая»
2я — «Получилось Ура»
3я — «Третья»

Привет! Формат .csv от обычного .txt практически ничем отличается, можно чуть больший данных объем записать и аля-excel сразу его преобразуют в таблицу.
Поэтому работать с этим файлом нужно как с обычным текстовым.
Считываем строки в массив, меняем нужную строку, переписываем весь файл, если такие изменения частые, то работаем с массивом, а переписываем файл по завершении скрипта и/или в OnClose() терминала.

Источник

I’m a beginner in lua (at best).

I have a *.lua script that at some point has a function that when called sets a set of variables. (or updates them) These specific variables should be extracted from a xls or csv file — something that can be managed by excel.

So in excel I have rows and columns like this:

valuefield_1 100 20 30

valuefield_2 60 150 40

valuefield_3 80 90 170

I want to be able to search for a specific valuefield through lua in xls/csv, for example «valuefield_1» and get the value in the third third column, which would be 20. This is then saved as variable x in my lua script so that whenever I call variable x, it uses the value 20 until I update variable x with a different value by searching for a different valuefield value.

In my efforts to find a solution to this (seemingly simply) issue, all I came across are xls modules for lua, how to output files, how to do graphs, complicated stuff far beyond what I want to do.

Isn’t there a simple way that I can have a line where it defines my variable by saying:

variable_x = value of the cell in the third column in the row of valuefield_x

so that I can simply set valuefield_x in my luascript according to what sort of valuefield I look for?

That’s really all I need, I don’t need to write xls/csv files or change anything in them. All I want is to accurately read specific cells in specific columns that are chosen by what «valuefield» I search for in the first column.

Can somebody tell me what the commands for that are?

2 Answers 2

Thanks for the answer, Schollii. The problem was pretty much that I didn’t even know how to begin with accessing, opening, editing or otherwise using Excel through lua, so any code example was pretty much useless. Thus I thought it best to describe what I required, rather than misdirecting with code snippets that dealt with entirely different things. (such as io.open and other things)

As always, after much — MUCH — research and browsing through 3 different manuals and rereading who knows how many irrelevant answers I came upon an answer that works for me. It’s actually very simple, so I cannot begin to imagine how many people could’ve spared me the hours and hours of research with a five minutes answer. Let’s hope that by providing a very thorough answer, I can ensure that other beginner like me who wish to do the same don’t have to do the same amount of research. And yes, the answer is very basic, and yes, I’m also explaining things most people who know lua code don’t need explained. This is for beginners like me.

Lua cannot — by itself — handle excel format, so instead you need to use the plugin LUACOM which is one of the modules installed through «Lua for Windows» It also includes a nifty script editor whith which you can right-click your scriptfile, click edit script, and you have a nice interface to edit and TEST your script.

The actual script:

The first part of your script requires you to utilize Excel through luacom.

a.The «require» line tells lua that it requires the module «luacom», to use the modules function for this lua script.

b. The second line through luacom opens an instance of Excel which is in the script referred to as «excel». This is necessary be able to target it with commands.

c. excel.Visible determines whether the open instance of excel can be seen by the user or whether its used invisible. Note how the «excel.» reference points at the instance we called «excel» in line 2.

(Alternative) It’s also possible to target an existing instance of excel that has already been opened manually by the user by replacing the second line with:

If we use the alternative way, and target an already open excel program, we can already target all the values in the first sheet. If we however create a new instance of excel, we have to open the file we wish to read from.

a. In the first line of this part, fpath determines the location of the xlsx file we wish to access. Note that «» are used instead of «».

b. We create the reference «wb» similar to the «excel reference in our first part of code. This one however opens a Workbook file (your excel file) at the location (fapth). Again, note how «excel.» points the code at the excel instance we created earlier.

c. This line determines which sheet is to be opened in the just opened Workbook file. In this case, it’s the sheet called «ImportantSheet1».

a. desired_name sets up the value that we seek (in this case a string)

b. Line 2 and 3 determine that the following process is to be done for rows 1-4 and columns 1-4, though you don’t have to call those «row» or «col».

c. The next line sets the value of the variable «current cell» to the value of the cell in excel at the position (x, y). You need to use «.Value2» (not «.Value») to in this command. So now our temporary variable has the cells value.

d. In the «if» command, we check if the current value of the cell is equal to the value we specified earlier as the «desired_name» which we seek.

e. If that is the case, «then» the next 3 lines set the Values 1-3 to the cells in the next columns in the same row. (So it «reads» from left to right the next values and saves them as our variable)

f. Finally, to check whether we actually have the values we want, we use the print command to view them when we execute the script. (This is, of course, not necessary to work with those values, this is merely here to check if this script works)

Источник

В помощь QLUA-водам. Функция чтения CSV файла.

В былую давность пытался решить вопрос с интерфейсом для QLUA.
Испробовал IUP, VCL и еще какая-то библиотека была. Но ни одна библиотека стабильно не работала, через какой-то промежуток времени Квик вставал колом.

Т.к. нам красоты не надо, а удобство хочется, то решил пусть интерфейсом будет Excel(файл.CSV).

Вот вам функция для чтения CSV файлов:

— можно задать до 20 столбиков параметров, количество строк не ограничено.
— запятую заменяет на точку в вещественном числе
— удаляет заголовок столбца, т.е. на выходе получаем массив начинающийся со второй строки

function File_Read(filename)

local col = 1
local pat = «(.*)»
local A=<>;local B=<>;local C=<>;local D=<>;local E=<>;
local F=<>;local G=<>;local H=<>;local I=<>;local J=<>;
local K=<>;local L=<>;local M=<>;local N=<>;local O=<>;
local P=<>;local Q=<>;local R=<>;local S=<>;local T=<>;
local file, err = io.open(filename,«r»)
if err

= nil then PrintDbgStr(«err read file: »..err); return; end
str = file:read()
for var in string.gmatch (str, «;») do col=col+1 end
for i = 2, col do pat = pat..»;(.*)» end
for line in io.lines(filename) do
—PrintDbgStr(line)
local _,_,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15,s16,s17,s18,s19,s20 = string.find(line,pat)
—PrintDbgStr(tostring(s1))
table.insert(A,s1);table.insert(B,s2);table.insert(C,s3);table.insert(D,s4);table.insert(E,s5);
table.insert(F,s6);table.insert(G,s7);table.insert(H,s8);table.insert(I,s9);table.insert(J,s10);
table.insert(K,s11);table.insert(L,s12);table.insert(M,s13);table.insert(N,s14);table.insert(O,s15);
table.insert(P,s16);table.insert(Q,s17);table.insert(R,s18);table.insert(S,s19);table.insert(T,s20);
end
file:close()
table.remove(A,1);table.remove(B,1);table.remove(C,1);table.remove(D,1);table.remove(E,1);
table.remove(F,1);table.remove(G,1);table.remove(H,1);table.remove(I,1);table.remove(J,1);
table.remove(K,1);table.remove(L,1);table.remove(M,1);table.remove(N,1);table.remove(O,1);
table.remove(P,1);table.remove(Q,1);table.remove(R,1);table.remove(S,1);table.remove(T,1);
—Print_Table® Print_Table(S) Print_Table(T)
return A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T
end

Во время работы робота смело изменяем CSV файл и сохраняем, и новые параметры у вас в роботе.
CSV файл можно держать открытым.

Источник

Главная » Основные форумы » Программирование на языке Lua

Страницы:
1

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#1

20.11.2022 01:38:18

Подскажите пожалуйста как в луа скрипт сделать так чтобы данные брались из excel таблицы? у меня есть такой индикатор для квика

Скрытый текст

я пытаюсь переделать его чтобы он мне рисовал каждые 5 минут 2 значения в виде гистограммы. значения будут браться из файла «test.xlsx» с компьютера. подскажите как сделать так чтобы скрипт считывал данные с excel? нужны ли какие то дополнительные программы? я скачал только notepad++, если можете подскажите хотябы как мне просто рисовать бар со значением 1 из таблицы excel чтобы хоть с чего то начать.

 

nikolz


Пользователь

Сообщений: 2735
Регистрация: 30.01.2015

#2

20.11.2022 06:41:23

поясните, вы будете брать данные из файла или из excel таблицы.
————————
если из файла, то как Вы в него хотите записывать.

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#3

20.11.2022 09:58:49

Цитата
nikolz написал:
поясните, вы будете брать данные из файла или из excel таблицы.
————————
если из файла, то как Вы в него хотите записывать.

Из файла, данные в файл будут выгружатся с сайта.

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#4

20.11.2022 10:03:47

Цитата
nikolz написал:
поясните, вы будете брать данные из файла или из excel таблицы.
————————
если из файла, то как Вы в него хотите записывать.

у меня есть excel файл с несколькими листами, на 1 листе подгружаются данные из файла csv (который скачивается с интернета), на 2 листе у меня распределены эти данные по времени начиная с 9-00 и до 24-00 в пятиминутном интервале. теперь из этого excel файла мне нужно перенести их в квик с помощью луа индикатора.

 

Nikolay


Пользователь

Сообщений: 710
Регистрация: 27.01.2017

#5

20.11.2022 10:04:52

Библиотека luaCom поможет открыть COM объект и прочитать файл. Но я не очень понимаю  зачем использовать тяжелый формат xls, а не перейти на простой текст с расширением csv, который читается очень просто, да и Excel открывает его как простую таблицу.

https://nick-nh.github.io/
https://github.com/nick-nh/qlua

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#6

20.11.2022 10:15:43

Цитата
Nikolay написал:
Библиотека luaCom поможет открыть COM объект и прочитать файл. Но я не очень понимаю  зачем использовать тяжелый формат xls, а не перейти на простой текст с расширением csv, который читается очень просто, да и Excel открывает его как простую таблицу.

в excele происходят некоторые операции сложения и вычитания с данными из csv файла, после чего получаются готовые данные которые необходимо перенести в квик. так как у меня нет опыта програмирования по логике я подумал что легче просто перенести готовые цифры в квик, чем производить в луа скрипте вычисления чтобы получить конечные данные (это я так думаю, конечно я могу ошибаться), не подскажешь какой нибудь видео урок где показывают как можно считывать либо excel файл либо csv файл (но тогда в самом скрипте нужно будет еще вычисления как то проводить) в луа. на ютюбе не нашел(

 

Nikolay


Пользователь

Сообщений: 710
Регистрация: 27.01.2017

#7

20.11.2022 10:25:36

Вычисления лучше в скрипте и произвести. И быстрее будет. Ексель нужен только когда это надо визуализировать, больше ни для чего он не нужен.
Я не очень понимаю это странное «учеба на YouTube». В книге от автора языка все написано очень просто и понятно. Да и примеров очень много как прочитать файл, если просто поискать.
А вот чтение xls — это уже использование сторонней библиотеки luaCOM. С учетом древности технологии COM, не думаю что будет много информации.

https://nick-nh.github.io/
https://github.com/nick-nh/qlua

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#8

20.11.2022 11:45:31

Цитата
Nikolay написал:
Вычисления лучше в скрипте и произвести. И быстрее будет. Ексель нужен только когда это надо визуализировать, больше ни для чего он не нужен.
Я не очень понимаю это странное «учеба на YouTube». В книге от автора языка все написано очень просто и понятно. Да и примеров очень много как прочитать файл, если просто поискать.
А вот чтение xls — это уже использование сторонней библиотеки luaCOM. С учетом древности технологии COM, не думаю что будет много информации.

Просто по видео хоть как то понятно, смотришь и повторяешь + автор какие то коментарии дает. Хочу начать с простого, хочу просто попробовать нарисовать свечу в 10:00 в поле индикатора со значением 10. нашел на форуме такой скрипт правильно ли я понимаю что этот скрипт просто рисует 2 свечи со значениями 5 и 10? если да то как допустим указать в какое время они должны рисоваться?

Скрытый текст

 

alexey


Пользователь

Сообщений: 8
Регистрация: 14.11.2022

#9

20.11.2022 13:50:00

у меня получилось с помощью вот такой функции

Скрытый текст

аккуратно, спойлер может лишить вас зрения. получается значения 11004, 11003 и т.д. отвечают за бар на графике. например 11004 это бар 18.11.2022 23:45, подскажите как сделать чтобы значения return он мне возвращал из моего файла csv и как мне сопоставить их по времени? в файле csv значения в таком виде 2022-11-18;23:00:00;1000, сначало идет дата, потом время, потом значение.

Страницы:
1

Читают тему (гостей: 1)

Here’s a full and minimal program demonstrating how to nest tables. Basically what you are missing is the lua_setfield function.

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
    int res;
    lua_State *L = lua_open();
    luaL_openlibs(L);

    lua_newtable(L); /* bottom table */

    lua_newtable(L); /* upper table */

    lua_pushinteger(L, 4);
    lua_setfield(L, -2, "four"); /* T[four] = 4 */
    lua_setfield(L, -2, "T");  /* name upper table field T of bottom table */
    lua_setglobal(L, "t"); /* set bottom table as global variable t */

    res = luaL_dostring(L, "print(t.T.four == 4)");
    if(res)
    {
        printf("Error: %sn", lua_tostring(L, -1));
    }

    return 0;
}

The program will simply print true.

If you need numeric indices, then you continue using lua_settable:

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
    int res;
    lua_State *L = lua_open();
    luaL_openlibs(L);

    lua_newtable(L); /* bottom table */

    lua_newtable(L); /* upper table */

    lua_pushinteger(L, 0);
    lua_pushinteger(L, 4);
    lua_settable(L, -3);  /* uppertable[0] = 4; pops 0 and 4 */
    lua_pushinteger(L, 0);
    lua_insert(L, -2); /* swap uppertable and 0 */
    lua_settable(L, -3); /* bottomtable[0] = uppertable */
    lua_setglobal(L, "t"); /* set bottom table as global variable t */

    res = luaL_dostring(L, "print(t[0][0] == 4)");
    if(res)
    {
        printf("Error: %sn", lua_tostring(L, -1));
    }

    return 0;
}

Rather than using absolute indices of 0 like I did, you might want to use lua_objlen to generate the index.

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Работа с excel таблицами для чайников бесплатно обучение
  • Работа с excel kotlin
  • Работа с excel счет
  • Работа с excel exe
  • Работа с excel статистические таблицы

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии