Unity сохранение в excel

Обновлено: 07.07.2024

Сколько я ни искал, всё как-то уж больно сложно и избыточно функционально.

А я хотел максимальной простоты — работать с таблицей как с двумерным массивом строк.

Ответ к которому я пришел - внизу :)

Полная поддержка CSV должна в себя включать:

  1. возможность изменять делимитер
  2. считывание ячеек между делимитерами
  3. считывание строк
  4. если знак делимитера есть в ячейке, ячейка должна братся в кавычки и нормально обрабатыватся самым ридером
  5. если знак перехода на следующую строку есть в ячейке, ячейка должна братся в кавычки и нормально обрабатыватся самим ридером.
  6. если ячейка выделена кавычками, а внутри есть кавычки, то они так же должны обрабатыватся без ошибок.


18k 4 4 золотых знака 28 28 серебряных знаков 90 90 бронзовых знаков хорошо работает только при количестве колонок не более 26 . если под работой с Excel понимаете простое считывание/сохранение данных это одно, если построение диаграмм - совсем другое @КонстантинПросекин не проверял, не нужно было так много колонок как-то. Если не забуду, через пару недель проверю и исправлю. Сейчас нету возможности :) @Ev_Hyper большинству людей под самые частые задачи достаточно считывания/сохранения данных. :)

Здесь я написал очень простую библиотеку на основе ClosedXML для того, чтобы не задумываясь иметь возможность работать с таблицами MS Excel как с двумерным массивом: что может быть легче в использовании?

Пример конечного кода для работы с моим классом:

Фактически, это и есть все методы — аскетский минимализм :)

Если нужно написать формулу, можно использовать следующий код:

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

Не будет работать, например, на Unity. Это из-за того, что пришось использовать библиотеку VB. Но в десктопных приложениях все ок.

Этот блок будет полезен тем, кому будет мало моей либы, и кто хочет больше возможностей в работе с Microsoft Excel.

Сначала я пытался работать с Excel-файлами при помощи Microsoft.Office.Interop.Excel, который по факту:

Считаю очень неудачным решением через него взаимодействовать.

И так я пришел к OpenXML. Как следствие — тоже относительно печальный опыт. Работать с ним просто-напросто неудобно. Не знаю, чем авторы думали.

И я пришел к конечному решению — обертки вокруг OpenXML - ClosedXML. Это решение уже позволило написать:

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


Пространства имен для добавления

public class ExcelAccess

public static string Excel = "Book";

// Запрос таблицы меню

public static List<Menu> SelectMenuTable()

string excelName = Excel + ".xlsx";

string sheetName = "sheet1";

DataRowCollection collect = ExcelAccess.ReadExcel(excelName, sheetName);

List<Menu> menuArray = new List<Menu>();

for (int i = 1; i < collect.Count; i++)

if (collect[i][1].ToString() == "") continue;

Menu menu = new Menu

/// Чтение Excel; необходимо добавить Excel.dll; System.Data.dll;

/// <param name = "excelName"> имя файла excel </ param>

/// <param name = "sheetName"> имя листа </ param>

/// <Return> DataRow Collection </ Return>

static DataRowCollection ReadExcel(string excelName,string sheetName)

string path= Application.dataPath + "/" + excelName;

FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

DataSet result = excelReader.AsDataSet();

//int columns = result.Tables[0].Columns.Count;

//int rows = result.Tables[0].Rows.Count;

// таблицы могут быть получены по имени листа или по индексу листа

Логика здесь очень проста. Если вы не знаете, вы можете перейти к документу Excel, чтобы увидеть его, но эта библиотека Excel имеет ограничение, то естьМогу только читать, но не писатьИ только вПод редакторомДа, если при загрузке и загрузке пакета сообщается об исключении нулевого указателя, причина неясна.

Поэтому я предлагаю всем позволить плану написать Excel и сохранить его в виде файла активов с классом Unity ScriptableObject после прочтения его в редакторе, который легче прочитать во время выполнения.

Использование ScriptableObject

Моя реализация приведена ниже. Вы можете написать этот BookHolder в соответствии с вашим собственным классом сущностей.

Unity-QuickSheet enables you to use google and excel spreadsheet data within Unity editor. With Unity-QuickSheet, you can retrieve data from a spreadsheet and save it as an asset file with a ScriptableObject format even without writing single line of code.


  • Easy! No need to write any single line of code.
  • Convenient! It can retrieve data from excel file. (both of xls and xlsx format are supported on Windows, only xls on OSX.)
  • Flexible! It can also retrieve data from google spreadsheet.
  • Fast! No need to write a parser to retrieve data, it automatically serializes retrieved data into Unity3D's ScriptableObject, the binary format and so it is fast than to use XML which is usually ASCII format.

Saying again, you don't need to write even single line of code to import data from a spreadsheet whatever Excel or Google spreadsheet.

Documentation, located on GitBook site found on here.

  • Release Note: See the Release page for change log.
  • Unity Forum: You can also find 'Unity-Quicksheet' on the Unity forum page found on here. Any feedbacks, patches or suggestions are always welcome!
    on Unity's forum for details of serialization mechanism. is used to retrieve data from Google Spreadsheet. Note that GDataDB is slightly modified to support enum type. is used to read xls and xlsx file.
  • All "*.dll" files of Google Data SDK are available at Google Data API SDK
  • Newtonsoft.Json source code for net 2.0 is available at here , my previous effort to import a spreadsheet data into Unity.

This code is distributed under the terms and conditions of the MIT license.

Other code or libraries borrowed from GDataDB, NPOI and Google Data API SDK follow its license.

Copyright (c) 2013 Kim, Hyoun Woo

About

Unity-QuickSheet enables you to use spreadsheet file data within Unity editor.

Unity Excel Importer

Automatically import from xls, xlsx to custom ScriptableObject in Unity Editor

1. Create Excel and add to Unity

Create an Excel file, make the first row the name of the column, and enter the data from the second row. And add it to Unity's Project view.

import_excel_to_unity

2. Create Entity Class Script

Create a new script and define a class with Excel column names and public fields of the desired type. Also give the class 'System.Serializable' attribute.

3. Create Excel Asset Script

After selecting Excel, execute ExcelAssetScript from the Create menu and create a ScriptableObject script for Excel.

create_excel_asset

As for the generated script, the Excel file name and the sheet name are extracted and the part is commented out as below.

4. Replace EntityType in created Excel Asset

Uncomment fields and replace the generic type of List with the Entity class defined above.

4. Reimport or re-save Excel

When you import or re-save Excel, a ScriptableObject with the same name as Excel is created in the same directory and the contents of Excel are imported.

reimport_excel

imported_entities

After this setting, updating Excel automatically updates ScriptableObject as well.

Change Asset Path

You can change the ScriptableObject generation position by specifying AssetPath as the ExcelAssetAttribute as shown below.

You can use enum by entering the element name as string in cell. It is also useful to set Data Validation pull down as an element of enum in Excel.

When true is specified for LogOnImport of ExcelAssetAttribute, a log is output when the import process runs.

Changing name association between ExcelAsset and ExcelFile

You can change the association to a specific Excel file by specifying ExcelName of ExcelAssetAttribute,

This library is under the MIT License. This software includes the work that is distributed in the Apache License 2.0.

Читайте также: