ワークシートにデータをインポート

ワークシートにデータをインポートする方法

Aspose.CellsでExcelファイルを開くと、ファイル内のすべてのデータが自動的にインポートされます。 Aspose.Cellsは他のデータソースからもデータをインポートできます。

Aspose.CellsはMicrosoft Excelファイルを表すWorkbookクラスを提供します。WorkbookクラスにはExcelファイルの各ワークシートにアクセスするためのWorksheetsコレクションが含まれています。ワークシートはWorksheetクラスによって表されます。WorksheetクラスはCellsコレクションを提供します。Cellsコレクションにはさまざまなデータソースからデータをインポートするための便利なメソッドが用意されています。この記事では、これらのメソッドの使用方法について説明します。

ICellsDataTableインターフェイスを使用してExcelにデータをインポートする方法

ICellsDataTableを実装してさまざまなデータソースをラップし、Cells.ImportData()を使用してExcelワークシートにデータをインポートします。

サンプルコード

//Init data source
CustomerList customers = new CustomerList();
customers.Add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
customers.Add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));
//Create a new file.
var wb = new Workbook();
ImportTableOptions options = new ImportTableOptions();
options.IsFieldNameShown = true;
//Import ICellsDataTable with options
wb.Worksheets[0].Cells.ImportData(new CustomerDataSource(customers), 0, 0, options);
wb.Save("ICellsDataTable.xlsx");

CustomerDataSource, Customer, CustomerList クラスの実装は以下のとおりです

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
public class CustomerDataSource : ICellsDataTable
{
public CustomerDataSource(CustomerList customers)
{
this.m_DataSource = customers;
this.m_Properties = customers[0].GetType().GetProperties();
this.m_Columns = new string[this.m_Properties.Length];
this.m_PropHash = new Hashtable(this.m_Properties.Length);
for (int i = 0; i < m_Properties.Length; i++)
{
this.m_Columns[i] = m_Properties[i].Name;
this.m_PropHash.Add(m_Properties[i].Name, m_Properties[i]);
}
this.m_IEnumerator = this.m_DataSource.GetEnumerator();
}
internal string[] m_Columns;
internal ICollection m_DataSource;
private Hashtable m_PropHash;
private IEnumerator m_IEnumerator;
private System.Reflection.PropertyInfo[] m_Properties;
public string[] Columns
{
get
{
return this.m_Columns;
}
}
public int Count
{
get
{
return this.m_DataSource.Count;
}
}
public void BeforeFirst()
{
this.m_IEnumerator = this.m_DataSource.GetEnumerator();
}
public object this[int index]
{
get
{
return this.m_Properties[index].GetValue(this.m_IEnumerator.Current, null);
}
}
public object this[string columnName]
{
get
{
return ((System.Reflection.PropertyInfo)this.m_PropHash[columnName]).GetValue(this.m_IEnumerator.Current, null);
}
}
public bool Next()
{
if (this.m_IEnumerator == null)
return false;
return this.m_IEnumerator.MoveNext();
}
}
public class Customer
{
public Customer(string aFullName, string anAddress)
{
FullName = aFullName;
Address = anAddress;
}
public string FullName { get; set; }
public string Address { get; set; }
}
public class CustomerList : ArrayList
{
public new Customer this[int index]
{
get { return (Customer)base[index]; }
set { base[index] = value; }
}
}

配列からExcelにデータをインポートする方法

配列からスプレッドシートにデータをインポートするには、ImportArrayコレクションのCellsメソッドを呼び出します。ImportArrayメソッドには多くのオーバーロードバージョンがありますが、典型的なオーバーロードでは次のパラメータが必要です:

  • Array、インポート元の配列オブジェクト。
  • 行番号、データがインポートされる最初のセルの行番号。
  • 列番号、データがインポートされる最初のセルの列番号。
  • 垂直、データを垂直または水平にインポートするかどうかを指定するブール値。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Creating an array containing names as string values
string[] names = new string[] { "laurence chen", "roman korchagin", "kyle huang" };
// Importing the array of names to 1st row and first column vertically
worksheet.Cells.ImportArray(names, 0, 0, true);
// Saving the Excel file
workbook.Save(dataDir + "DataImport.out.xls");

配列リストからExcelにデータをインポートする方法

ArrayListからワークシートにデータをインポートするには、CellsコレクションのImportArrayListメソッドを呼び出します。ImportArrayメソッドには次のパラメータが必要です:

  • ArrayList、インポート元のArrayListを表す。
  • 行番号、データがインポートされる最初のセルの行番号を表す。
  • 列番号、データがインポートされる最初のセルの列番号を表す。
  • 垂直、データを垂直または水平にインポートするかどうかを指定するブール値。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Instantiating an ArrayList object
ArrayList list = new ArrayList();
// Add few names to the list as string values
list.Add("laurence chen");
list.Add("roman korchagin");
list.Add("kyle huang");
list.Add("tommy wang");
// Importing the contents of ArrayList to 1st row and first column vertically
worksheet.Cells.ImportArrayList(list, 0, 0, true);
// Saving the Excel file
workbook.Save(dataDir + "DataImport.out.xls");

カスタムオブジェクトからExcelにデータをインポートする方法

オブジェクトのコレクションからワークシートにデータをインポートするには、ImportCustomObjectsを使用します。表示する希望のオブジェクトのリストをメソッドに提供します。

private void TestImportingFromCustomObject()
{
//Examples-CSharp-Data-Handling-Importing-ImportingFromCustomObject-1.cs
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiate a new Workbook
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
// Define List
List<Person> list = new List<Person>();
list.Add(new Person("Mike", 25));
list.Add(new Person("Steve", 30));
list.Add(new Person("Billy", 35));
ImportTableOptions imp = new ImportTableOptions();
imp.InsertRows = true;
// We pick a few columns not all to import to the worksheet
// We pick a few columns not all to import to the worksheet
sheet.Cells.ImportCustomObjects((System.Collections.ICollection)list,
new string[] { "Name", "Age" },
true,
0,
0,
list.Count,
true,
"dd/mm/yyyy",
false);
// Auto-fit all the columns
book.Worksheets[0].AutoFitColumns();
// Save the Excel file
book.Save(dataDir + "ImportedCustomObjects.out.xls");
}
class Person
{
int _age;
string _name;
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public Person(string name, int age)
{
Age = age;
Name = name;
}
}

カスタムオブジェクトからExcelにデータをインポートし、マージされたエリアをチェックする方法

オブジェクトのコレクションからマージされたセルを含むワークシートにデータをインポートするには、ImportTableOptions.CheckMergedCellsプロパティを使用します。Excelテンプレートにマージされたセルがある場合は、ImportTableOptions.CheckMergedCellsプロパティの値をtrueに設定します。メソッドに表示する希望のオブジェクトのリストとともにImportTableOptionsオブジェクトを渡します。次のコードサンプルは、ImportTableOptions.CheckMergedCellsプロパティを使用してカスタムオブジェクトからマージされたセルにデータをインポートする方法を示しています。参考のために添付のソースExcelファイルと出力Excelファイルをご覧ください。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
public class ImportCustomObjectsToMergedArea
{
public static void Run()
{
//Source directory
string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
string outputDir = RunExamples.Get_OutputDirectory();
Workbook workbook = new Workbook(sourceDir + "sampleMergedTemplate.xlsx");
List<Product> productList = new List<Product>();
//Creating collection of test items
for (int i = 0; i < 3; i++)
{
Product product = new Product
{
ProductId = i,
ProductName = "Test Product - " + i
};
productList.Add(product);
}
ImportTableOptions tableOptions = new ImportTableOptions();
tableOptions.CheckMergedCells = true;
tableOptions.IsFieldNameShown = false;
//Insert data to excel template
workbook.Worksheets[0].Cells.ImportCustomObjects((ICollection)productList, 1, 0, tableOptions);
workbook.Save(outputDir + "sampleMergedTemplate_out.xlsx", SaveFormat.Xlsx);
Console.WriteLine("ImportCustomObectsToMergedArea executed successfully.\r\n");
}
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}

ExcelからDataTableにデータをインポートする方法

DataTableからデータをインポートするには、CellsコレクションのImportDataTableメソッドを呼び出します。ImportDataTableメソッドにはオーバーロードされたバージョンが多数ありますが、典型的なオーバーロードは次のパラメータを取ります:

  • Data table: インポート元のDataTableオブジェクト。
  • フィールド名の表示: DataTableの列名をワークシートに最初の行としてインポートするかどうかを指定します。
  • 開始セル: DataTableの内容をインポートする開始セルの名前 (例: “A1”) を表します。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Instantiating a "Products" DataTable object
DataTable dataTable = new DataTable("Products");
// Adding columns to the DataTable object
dataTable.Columns.Add("Product ID", typeof(Int32));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(Int32));
// Creating an empty row in the DataTable object
DataRow dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 1;
dr[1] = "Aniseed Syrup";
dr[2] = 15;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
// Creating another empty row in the DataTable object
dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 2;
dr[1] = "Boston Crab Meat";
dr[2] = 123;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
ImportTableOptions tableOptions = new ImportTableOptions();
// Importing the contents of DataTable to the worksheet starting from "A1" cell,
// Where true specifies that the column names of the DataTable would be added to
// The worksheet as a header row
tableOptions.IsFieldNameShown = true;
worksheet.Cells.ImportData(dataTable, 0, 0, tableOptions);
// Saving the Excel file
workbook.Save(dataDir + "DataImport.out.xls");

Excelから動的オブジェクトをデータソースとしてデータをインポートする方法

Aspose.Cellsは、動的オブジェクトをデータソースとして使用する機能を提供しています。そこでは、プロパティがオブジェクトに動的に追加されます。プロパティがオブジェクトに追加された後、Aspose.Cellsは最初のエントリをテンプレートとして扱い、それ以降に応じて処理します。つまり、最初のアイテムのみに動的プロパティが追加され、他のオブジェクトには追加されていない場合、Aspose.Cellsはコレクション内のすべてのアイテムが同じであると見なします。

この例では、最初は2つの変数のみを含むテンプレートモデルが使用されています。このリストは動的オブジェクトのリストに変換されます。その後、追加のフィールドが追加され、最後にワークブックにロードされます。ワークブックはテンプレートXLSXファイル内の値のみを取得します。このテンプレートワークブックにはパラメータを含むスマートマーカーが使用されています。パラメータを使用すると、情報の配置方法を変更できます。スマートマーカーの詳細については、次の記事から取得できます:

スマートマーカーの使用

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
using System.Collections.Generic;
using System.Dynamic;
using System.ComponentModel;
using System.Linq;
namespace Aspose.Cells.Examples.CSharp.Data.Handling.Importing
{
public class ImportingFromDynamicDataTable
{
//Source directory
static string sourceDir = RunExamples.Get_SourceDirectory();
//Output directory
static string outputDir = RunExamples.Get_OutputDirectory();
public static void Run()
{
// ExStart:1
// Here data is filled into a list of Model class containing two fields only
var data = GetData();
// Based upon business some additional fields e.g. unique id is added
var modifiedData = new Converter().GetModifiedData(data);
// Modified data is still an object but it is a dynamic one now
modifiedData.First().Id = 20;
// Following field is added in the dynamic objects list, but it will not be added to workbook as template file does not have this field
modifiedData.First().Id2 = 200;
// Create workbook and fill it with the data
Workbook workbook = new Workbook(sourceDir + @"ExcelTemplate.xlsx");
WorkbookDesigner designer = new WorkbookDesigner(workbook);
designer.SetDataSource("modifiedData", modifiedData);
designer.Process();
designer.Workbook.Save(outputDir + @"ModifiedData.xlsx");
// Base Model does work but doesn't have the Id
Workbook workbookRegular = new Workbook(sourceDir + @"ExcelTemplate.xlsx");
WorkbookDesigner designerRegular = new WorkbookDesigner(workbookRegular);
designerRegular.SetDataSource("ModifiedData", data);
designerRegular.Process();
designerRegular.Workbook.Save(outputDir + @"ModifiedDataRegular.xlsx");
// ExEnd:1
}
private static List<Model> GetData()
{
return new List<Model>
{
new Model{ Code = 1 , Name = "One" },
new Model{ Code = 2 , Name = "Two" },
new Model{ Code = 3 , Name = "Three" },
new Model{ Code = 4 , Name = "Four" },
new Model{ Code = 5 , Name = "Five" }
};
}
}
public class Model
{
public string Name { get; internal set; }
public int Code { get; internal set; }
}
public class Converter
{
private int _uniqueNumber;
public List<dynamic> GetModifiedData(List<Model> data)
{
var result = new List<dynamic>();
result.AddRange(data.ConvertAll<dynamic>(i => AddId(i)));
return result;
}
private dynamic AddId(Model i)
{
var result = TransformToDynamic(i);
result.Id = GetUniqueNumber();
return result;
}
private int GetUniqueNumber()
{
var result = _uniqueNumber;
_uniqueNumber++;
return result;
}
private dynamic TransformToDynamic(object dataObject)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(dataObject.GetType()))
expando.Add(property.Name, property.GetValue(dataObject));
return expando as dynamic;
}
}
}

DataColumnをExcelにインポートする方法

A DataTableまたはDataViewオブジェクトは1つ以上の列で構成されています。開発者は、DataTableまたはDataViewの列/列からデータをインポートするために、CellsコレクションのImportDataメソッドを呼び出すこともできます。ImportDataメソッドはImportTableOptions型のパラメータを受け入れます。ImportTableOptionsクラスはColumnIndexesプロパティを提供し、列のインデックスの配列を受け入れます。

以下に示すサンプルコードは、ImportTableOptions.ColumnIndexesの使用を示しています。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a "Products" DataTable object
DataTable dataTable = new DataTable("Products");
// Adding columns to the DataTable object
dataTable.Columns.Add("Product ID", typeof(Int32));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(Int32));
// Creating an empty row in the DataTable object
DataRow dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 1;
dr[1] = "Aniseed Syrup";
dr[2] = 15;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
// Creating another empty row in the DataTable object
dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 2;
dr[1] = "Boston Crab Meat";
dr[2] = 123;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
// Instantiate a new Workbook
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
// Create import options
ImportTableOptions importOptions = new ImportTableOptions();
importOptions.IsFieldNameShown = true;
importOptions.IsHtmlString = true;
// Importing the values of 2nd column of the data table
sheet.Cells.ImportData(dataTable, 1, 1, importOptions);
// Save workbook
book.Save(dataDir + "DataImport.out.xls");

DataViewをExcelにインポートする方法

DataViewからデータをインポートするには、CellsコレクションのImportDataメソッドを呼び出します。ImportDataメソッドにはオーバーロードされたバージョンが多数ありますが、DataView用の典型的なオーバーロードは次のパラメータを取ります:

  • DataView: インポート元のDataView オブジェクト。
  • 最初の行: データがインポートされる最初のセルの行番号。
  • 最初の列: データがインポートされる最初のセルの列番号。
  • ImportTableOptions: インポートオプション。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Instantiating a "Products" DataTable object
DataTable dataTable = new DataTable("Products");
// Adding columns to the DataTable object
dataTable.Columns.Add("Product ID", typeof(Int32));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(Int32));
// Creating an empty row in the DataTable object
DataRow dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 1;
dr[1] = "Aniseed Syrup";
dr[2] = 15;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
// Creating another empty row in the DataTable object
dr = dataTable.NewRow();
// Adding data to the row
dr[0] = 2;
dr[1] = "Boston Crab Meat";
dr[2] = 123;
// Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
// Importing the contents of the data view to the worksheet
ImportTableOptions options = new ImportTableOptions();
options.IsFieldNameShown = true;
worksheet.Cells.ImportData(dataTable.DefaultView, 0, 0, options);
// Saving the Excel file
workbook.Save(dataDir + "output.xls");

DataGridをExcelにインポートする方法

DataGridからデータをインポートすることができます。その際には、CellsコレクションのImportDataGridメソッドを呼び出します。ImportDataGridメソッドには多数のオーバーロードバージョンがありますが、典型的なオーバーロードは次のパラメータを取ります:

  • Data grid: インポート元のDataGrid オブジェクト。
  • Row Number: データがインポートされる最初のセルの行番号。
  • Column Number: データがインポートされる最初のセルの列番号。
  • Insert Rows: データを格納するためにワークシートに余分な行を追加するかどうかを示すブール値。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create a DataTable object and set it as DataSource of DataGrid.
DataTable dataTable = new DataTable("Products");
dataTable.Columns.Add("Product ID", typeof(Int32));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(Int32));
DataRow dr = dataTable.NewRow();
dr[0] = 1;
dr[1] = "Aniseed Syrup";
dr[2] = 15;
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr[0] = 2;
dr[1] = "Boston Crab Meat";
dr[2] = 123;
dataTable.Rows.Add(dr);
// Now take care of DataGrid
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dataTable;
dg.DataBind();
// We have a DataGrid object with some data in it.
// Lets import it into our spreadsheet
// Creat a new workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
// Importing the contents of the data grid to the worksheet
worksheet.Cells.ImportDataGrid(dg, 0, 0, false);
// Save it as Excel file
workbook.Save(dataDir + "output.xlsx");

GridViewをExcelにインポートする方法

GridView コントロールからデータをインポートするには、CellsコレクションのImportGridViewメソッドを呼び出します。

Aspose.Cellsを使用すると、データをスプレッドシートにインポートする際にHTML形式の値を正しく解釈することができます。HTMLの解析を有効にしてデータをインポートすると、Aspose.CellsはHTMLを対応するセルの書式設定に変換します。

ExcelにHTML形式のデータをインポートする方法

Aspose.Cellsは、外部データソースからデータをインポートするための非常に有用なメソッドを提供するCells クラスを提供しています。この記事では、データをインポートする際にHTML形式のテキストを解析し、HTMLを書式設定されたセルの値に変換する方法を示します。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string output1Path = dataDir + "Output.out.xlsx";
string output2Path = dataDir + "Output.out.ods";
// Prepare a DataTable with some HTML formatted values
DataTable dataTable = new DataTable("Products");
dataTable.Columns.Add("Product ID", typeof(Int32));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(Int32));
DataRow dr = dataTable.NewRow();
dr[0] = 1;
dr[1] = "<i>Aniseed</i> Syrup";
dr[2] = 15;
dataTable.Rows.Add(dr);
dr = dataTable.NewRow();
dr[0] = 2;
dr[1] = "<b>Boston Crab Meat</b>";
dr[2] = 123;
dataTable.Rows.Add(dr);
// Create import options
ImportTableOptions importOptions = new ImportTableOptions();
importOptions.IsFieldNameShown = true;
importOptions.IsHtmlString = true;
// Create workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Cells.ImportData(dataTable, 0, 0, importOptions);
worksheet.AutoFitRows();
worksheet.AutoFitColumns();
workbook.Save(output1Path);
workbook.Save(output2Path);

JSONからExcelにデータをインポートする方法

Aspose.Cellsは、JSONを処理するためのJsonUtilityクラスを提供しています。JsonUtilityクラスには、JSONデータをインポートするためのImportDataメソッドがあります。Aspose.Cellsは、JSONレイアウトのオプションを表すJsonLayoutOptionsクラスも提供しています。ImportDataメソッドは、パラメータとしてJsonLayoutOptionsを受け入れます。JsonLayoutOptionsクラスには、以下のプロパティが用意されています。

  • ArrayAsTable:配列内の処理がテーブルとして行われるかどうかを示します。
  • ConvertNumericOrDate:JSON内の文字列を数値または日付に変換するかどうかを取得または設定します。
  • DateFormat:日付値の形式を取得および設定します。
  • IgnoreArrayTitle:オブジェクトのプロパティが配列の場合に、タイトルを無視するかどうかを示します。
  • IgnoreNull:null値を無視するかどうかを示します。
  • IgnoreObjectTitle:オブジェクトのプロパティがオブジェクトの場合に、タイトルを無視するかどうかを示します。
  • NumberFormat:数値値の形式を取得および設定します。
  • TitleStyle:タイトルのスタイルを取得および設定します。

以下のサンプルコードは、JsonUtilityおよびJsonLayoutOptionsクラスを使用してJSONデータをインポートする方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
// Read File
string jsonInput = File.ReadAllText(dataDir + "Test.json");
// Set Styles
CellsFactory factory = new CellsFactory();
Style style = factory.CreateStyle();
style.HorizontalAlignment = TextAlignmentType.Center;
style.Font.Color = System.Drawing.Color.BlueViolet;
style.Font.IsBold = true;
// Set JsonLayoutOptions
JsonLayoutOptions options = new JsonLayoutOptions();
options.TitleStyle = style;
options.ArrayAsTable = true;
// Import JSON Data
JsonUtility.ImportData(jsonInput, worksheet.Cells, 0, 0, options);
// Save Excel file
workbook.Save(dataDir + "ImportingFromJson.out.xlsx");

高度なトピック