Importar datos en hoja de cálculo
Cómo Importar Datos en una Hoja de Cálculo
Cuando abres un archivo de Excel con Aspose.Cells, todos los datos en el archivo se importan automáticamente. Aspose.Cells también puede importar datos de otras fuentes de datos.
Aspose.Cells proporciona una clase Workbook que representa un archivo de Microsoft Excel. La clase Workbook contiene una colección Worksheets que permite acceder a cada hoja de cálculo en un archivo de Excel. Una hoja de cálculo está representada por la clase Worksheet. La clase Worksheet proporciona una colección Cells. La colección Cells proporciona métodos útiles para importar datos desde diferentes fuentes de datos. Este artículo explica cómo se pueden utilizar estos métodos.
Cómo Importar datos en Excel con la interfaz ICellsDataTable
Implementa ICellsDataTable para envolver tus diversas fuentes de datos, luego usa Cells.ImportData() para importar datos en la hoja de cálculo de Excel.
Código de muestra
//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"); |
A continuación se presenta la implementación de las clases CustomerDataSource, Customer y 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; } | |
} | |
} |
Cómo Importar Datos en Excel desde un Array
Para importar datos a una hoja de cálculo desde un array, llama al método ImportArray de la colección Cells. Hay muchas versiones sobrecargadas del método ImportArray pero una sobrecarga típica toma los siguientes parámetros:
- Array, el objeto array desde el que estás importando contenido.
- Número de fila, el número de fila de la primera celda a la que se importarán los datos.
- Número de columna, el número de columna de la primera celda a la que se importarán los datos.
- Es vertical, un valor booleano que especifica si se importarán los datos vertical u horizontalmente.
// 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"); |
Cómo Importar Datos en Excel desde un ArrayList
Para importar datos desde un ArrayList a hojas de cálculo, llama al método ImportArrayList de la colección Cells. El método ImportArray toma los siguientes parámetros:
- Lista de array, representa el objeto ArrayList que estás importando.
- Número de fila, representa el número de fila de la primera celda a la que se importarán los datos.
- Número de columna, representa el número de columna de la primera celda a la que se importarán los datos.
- Es vertical, un valor booleano que especifica si se importarán los datos vertical u horizontalmente.
// 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"); |
Cómo importar datos en Excel desde objetos personalizados
Para importar datos de una colección de objetos a una hoja de cálculo, use ImportCustomObjects. Proporcione una lista de columnas/propiedades al método para mostrar su lista deseada de objetos.
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; | |
} | |
} |
Cómo importar datos en Excel desde objetos personalizados y verificar el área combinada
Para importar datos de una colección de objetos a una hoja de cálculo que contiene celdas combinadas, use la propiedad ImportTableOptions.CheckMergedCells. Si la plantilla de Excel tiene celdas combinadas, establezca el valor de la propiedad ImportTableOptions.CheckMergedCells en true. Pase el objeto ImportTableOptions junto con la lista de columnas/propiedades al método para mostrar su lista deseada de objetos. El siguiente ejemplo de código demuestra el uso de la propiedad ImportTableOptions.CheckMergedCells para importar datos de objetos personalizados a celdas combinadas. Consulte el archivo de Excel adjunto de origen (90112033.xlsx) y el archivo de Excel de salida (90112034.xlsx) para obtener más información.
// 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; } | |
} |
Cómo importar datos en Excel desde un DataTable
Para importar datos desde un DataTable, llame al método ImportDataTable de la colección Cells. Existen muchas versiones sobrecargadas del método ImportDataTable, pero una sobrecarga típica toma los siguientes parámetros:
- DataTable, el objeto DataTable desde el cual está importando el contenido.
- Se muestra el nombre de campo, especifica si los nombres de las columnas de DataTable deben importarse a la hoja de cálculo como primera fila o no.
- Celda de inicio, representa el nombre de la celda de inicio (por ejemplo, “A1”) desde donde importar los contenidos de DataTable.
// 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"); |
Cómo importar datos en Excel desde un objeto dinámico como fuente de datos
Aspose.Cells proporciona características para trabajar con objetos dinámicos como fuente de datos. Esto ayuda en el uso de una fuente de datos donde las propiedades se agregan dinámicamente a los objetos. Una vez que las propiedades se agregan al objeto, Aspose.Cells considera la primera entrada como la plantilla y maneja el resto en consecuencia. Esto significa que si alguna propiedad dinámica se agrega solo a un primer elemento y no a otros objetos, Aspose.Cells considera que todos los elementos en la colección deberían ser iguales.
En este ejemplo, se utiliza un modelo de plantilla que inicialmente contiene solo dos variables. Esta lista se convierte en una lista de objetos dinámicos. Luego se agrega algún campo adicional y finalmente se carga en el libro de trabajo. El libro de trabajo recoge solo esos valores que están en el archivo XLSX de plantilla. Este libro de trabajo de plantilla utiliza Marcadores Inteligentes que también contienen parámetros. Los parámetros le permiten modificar cómo se muestra la información. Los detalles sobre los Marcadores Inteligentes se pueden obtener del siguiente artículo:
Usando Marcadores Inteligentes
// 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; | |
} | |
} | |
} |
Cómo importar DataColumn en Excel
Un objeto DataTable o DataView está compuesto por una o más columnas. Los desarrolladores también pueden importar datos de cualquier columna/columnas del DataTable o DataView llamando al método ImportData de la colección Cells. El método ImportData acepta un parámetro de tipo ImportTableOptions. La clase ImportTableOptions proporciona una propiedad ColumnIndexes que acepta una matriz de índices de columnas.
El código de muestra a continuación demuestra el uso de ImportTableOptions.ColumnIndexes para importar columnas selectivas.
// 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"); |
Cómo importar DataView en Excel
Para importar datos desde un DataView, llame al método ImportData de la colección Cells. Existen muchas versiones sobrecargadas del método ImportData, pero la de DataView toma los siguientes parámetros:
- DataView: El objeto DataView del cual vas a importar contenido.
- Primera fila: el número de fila de la primera celda a la que se importarán los datos.
- Primera columna: el número de columna de la primera celda a la que se importarán los datos.
- Opciones de importación de tabla: Las opciones de importación.
// 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"); |
Cómo importar DataGrid a Excel
Es posible importar datos de un DataGrid llamando al método ImportDataGrid de la colección Cells. Hay muchas versiones sobrecargadas del método ImportDataGrid pero una sobrecarga típica toma los siguientes parámetros:
- Data grid, el objeto DataGrid del cual estás importando contenido.
- Número de fila, el número de fila de la primera celda a la que se importarán los datos.
- Número de columna, el número de columna de la primera celda a la que se importarán los datos.
- Insertar filas, una propiedad booleana que indica si se deben agregar filas adicionales a la hoja de cálculo para ajustar los datos o no.
// 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"); |
Cómo importar GridView a Excel
Para importar datos desde un control GridView, llama al método ImportGridView de la colección Cells.
Aspose.Cells nos permite respetar los valores formateados en HTML al importar datos a la hoja de cálculo. Cuando se habilita el análisis de HTML al importar datos, Aspose.Cells convierte el HTML en el formato de celda correspondiente.
Cómo importar datos con formato HTML a Excel
Aspose.Cells proporciona una clase Cells que ofrece métodos muy útiles para importar datos desde fuentes de datos externas. Este artículo muestra cómo analizar texto con formato HTML al importar datos y convertir el HTML en valores de celda formateados.
// 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); |
Cómo importar datos a Excel desde JSON
Aspose.Cells proporciona una clase JsonUtility para procesar JSON. La clase JsonUtility tiene un método ImportData para importar datos JSON. Aspose.Cells también proporciona una clase JsonLayoutOptions que representa las opciones del diseño JSON. El método ImportData acepta JsonLayoutOptions como parámetro. La clase JsonLayoutOptions proporciona las siguientes propiedades.
- ArrayAsTable: Indica si el arreglo debe procesarse como una tabla o no.
- ConvertNumericOrDate: Obtiene o establece un valor que indica si la cadena en JSON debe convertirse a numérico o fecha.
- DateFormat: Obtiene y establece el formato del valor de fecha.
- IgnoreArrayTitle: Indica si se debe omitir el título si la propiedad del objeto es un arreglo.
- IgnoreNull: Indica si el valor nulo debe ser ignorado o no.
- IgnoreObjectTitle: Indica si se debe ignorar el título si la propiedad del objeto es un objeto.
- NumberFormat: Obtiene y establece el formato del valor numérico.
- TitleStyle: Obtiene y establece el estilo del título.
El código de muestra que se muestra a continuación demuestra el uso de las clases JsonUtility y JsonLayoutOptions para importar datos 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"); |