엑셀로 데이터 내보내기

이 기사에서는 배열, 사용자 지정 개체 컬렉션, DataTable, DataView, DataGrid, GridView, HTML, JSON 및 CSV와 같은 다양한 데이터 원본에서 C# 및 VB.NET의 Excel로 데이터를 내보내는 방법을 보여줍니다.

Aspose.Cells API를 사용하여 C#에서 Excel로 데이터 내보내기

Aspose.Cells for .NET은 .NET 응용 프로그램 내에서 Excel 파일을 생성, 편집 또는 변환할 수 있는 강력한 스프레드시트 조작 API입니다. API의 사용하기 쉬운 메서드를 사용하면 몇 줄의 코드로 Excel 자동화 기능을 원활하게 수행할 수 있습니다. NuGet은 .NET용 Aspose.Cells API를 다운로드하고 설치하는 가장 쉬운 방법입니다. NuGet 패키지 관리 창을 열고 검색 텍스트 상자에 “Aspose.Cells"를 입력하여 Aspose.Cells .NET 패키지를 찾습니다. 마지막으로 설치 버튼을 클릭하여 최신 버전의 패키지를 설치합니다.

C#에서 Excel로 배열 내보내기

참조 유형 또는 값 유형의 배열(1차원 또는 2차원)을 Excel 문서로 내보낼 수 있습니다. Cells 컬렉션의 ImportArray 메서드를 사용하여 배열에서 스프레드시트로 데이터를 내보냅니다. ImportArray 메서드의 오버로드 버전은 다음과 같습니다.

이름설명
ImportArray(Double[], Int32, Int32, Boolean)double형 배열을 워크시트로 내보냅니다.
ImportArray(Int32[], Int32, Int32, Boolean)정수 배열을 워크시트로 내보냅니다.
ImportArray(String[], Int32, Int32, Boolean)문자열 배열을 워크시트로 내보냅니다.
ImportArray(Double[,], Int32, Int32)double의 2차원 배열을 워크시트로 내보냅니다.
ImportArray(Int32[,], Int32, Int32)정수의 2차원 배열을 워크시트로 내보냅니다.
ImportArray(String[,], Int32, Int32)2차원 문자열 배열을 워크시트로 내보냅니다.

일반적인 과부하는 다음 매개변수를 사용합니다.

  • Array, 콘텐츠를 내보내는 배열 객체입니다.
  • 행 번호, 데이터를 내보낼 첫 번째 셀(0부터 시작)의 행 번호입니다.
  • 열 번호, 데이터를 내보낼 첫 번째 셀(0부터 시작)의 열 번호입니다.
  • 세로 또는 가로로 데이터를 내보낼지 여부를 지정하는 부울 값입니다.

다음은 C#에서 배열을 Excel 파일로 내보내는 단계입니다.

  • Workbook 개체를 만듭니다. Workbook 클래스는 Microsoft Excel 파일을 나타냅니다.
  • 원하는 워크시트에 대한 참조를 가져옵니다. Workbook 클래스에는 Excel 파일의 각 워크시트에 액세스할 수 있는 Worksheets 컬렉션이 포함되어 있습니다.
  • Cells 컬렉션의 ImportArray 메서드를 호출하여 워크시트의 지정된 행과 열에 배열을 내보냅니다. Worksheet 클래스는 Cells 컬렉션을 제공합니다.
  • Workbook.Save(string) 메서드를 사용하여 Excel 파일을 저장합니다.

다음 코드 샘플은 C#에서 문자열 배열을 Excel 파일로 내보내는 방법을 보여줍니다.

// 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" };

// Exporting the array of names to first row and first column vertically
worksheet.Cells.ImportArray(names, 0, 0, true);

// Saving the Excel file
workbook.Save("StringsArray.xlsx");
문자열 배열을 Excel로 내보내기

데이터 배열을 Excel로 내보내기

마찬가지로 2차원 배열을 Excel 파일로 내보낼 수 있습니다. 다음 코드 샘플은 C#에서 2차원 배열을 Excel 파일로 내보내는 방법을 보여줍니다.

// Creating a two-dimensional array of integers
int[,] array2D = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

// Exporting a two-dimensional array at the first row and first column of the worksheet
worksheet.Cells.ImportArray(array2D, 0, 0);

C#에서 ArrayList를 Excel로 내보내기

ArrayList에서 워크시트로 데이터를 내보내려면 Cells 컬렉션의 ImportArrayList 메서드를 호출합니다. ImportArrayList 메서드는 다음 매개변수를 사용합니다.

  • 배열 목록은 내보내는 ArrayList 개체를 나타냅니다.
  • 행 번호는 데이터를 내보낼 첫 번째 셀의 행 번호를 나타냅니다.
  • 열 번호는 데이터를 내보낼 첫 번째 셀의 열 번호를 나타냅니다.
  • 수직 또는 수평으로 데이터를 내보낼지 여부를 지정하는 부울 값입니다.

다음 코드 샘플은 C#에서 ArrayList를 Excel 파일로 내보내는 방법을 보여줍니다.

// 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");

// Exporting the contents of ArrayList vertically at the first row and first column of the worksheet. 
worksheet.Cells.ImportArrayList(list, 0, 0, true);

// Saving the Excel file
workbook.Save("ArrayListExport.xlsx");

C#에서 Excel로 사용자 지정 개체 컬렉션 내보내기

사용자 지정 개체 컬렉션에서 워크시트로 데이터를 내보내려면 ImportCustomObjects 메서드를 사용합니다. 이 메서드에는 두 가지 오버로드된 버전이 있습니다.

  1. ImportCustomObjects(ICollection list, String[] propertyNames, Boolean isPropertyNameShown, Int32 firstRow, Int32 firstColumn, Int32 rowNumber, Boolean 삽입, String dateFormatString, Boolean convertStringToNumber)
  2. ImportCustomObjects(ICollection 목록, Int32 firstRow, Int32 firstColumn, ImportTableOptions 옵션)

오버로드된 각 메서드를 하나씩 살펴보겠습니다. 첫 번째 오버로드된 메서드의 매개 변수에 대한 설명은 다음과 같습니다.

  • 사용자 정의 개체의 컬렉션을 나열합니다.
  • propertyNames 내보낼 개체의 속성 이름입니다. null이면 모든 속성을 내보냅니다.
  • isPropertyNameShown 속성 이름을 첫 번째 행으로 내보낼지 여부를 나타냅니다.
  • firstRow 내보낼 첫 번째 셀의 행 번호입니다.
  • firstColumn 내보낼 첫 번째 셀의 열 번호입니다.
  • rowNumber 내보낼 객체의 수입니다.
  • insertRows 데이터에 맞게 추가 행을 추가할지 여부를 나타냅니다.
  • dateFormatString 셀의 날짜 형식 문자열입니다.
  • convertStringToNumber 이 메서드가 문자열을 숫자로 변환하려고 하는지 여부를 나타냅니다.

다음 예제에서는 Person 개체 목록을 C#의 Excel 문서로 내보내고 있습니다. Person 개체의 두 가지 속성(Name 및 Age)만 내보내고 있다는 점에 유의하십시오.

// Instantiate a new Workbook
Workbook book = new Workbook();
// Obtaining the reference of the worksheet
Worksheet sheet = book.Worksheets[0];

// Define List
List<Person> list = new List<Person>();

list.Add(new Person("Mike", 25, "Software Engineer"));
list.Add(new Person("Steve", 30, "Doctor"));
list.Add(new Person("Billy", 35, "Teacher"));

// We pick only Name and Age columns, not all, to export to the worksheet         
sheet.Cells.ImportCustomObjects((System.Collections.ICollection)list,
    new string[] { "Name", "Age" }, // propertyNames
    true, // isPropertyNameShown
    0, // firstRow
    0, // firstColumn
    list.Count, // Number of objects to be exported
    true, // insertRows
    null, // dateFormatString
    false); // convertStringToNumber

// Save the Excel file
book.Save("ExportedCustomObjects.xlsx");
       
public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }

    public string Occupation { get; set; }

    public Person(string name, int age, string occupation)
    {
        Age = age;
        Name = name;
        Occupation = occupation;
    }
}
Excel로 개체 목록 내보내기

Person 개체 목록을 Excel로 내보내기

이제 ImportCustomObjects의 두 번째 오버로드된 메서드를 살펴봅니다. 방법의 매개변수에 대한 설명은 다음과 같습니다.

  • list 사용자 정의 개체 목록.
  • firstRow 내보낼 첫 번째 셀의 행 번호입니다.
  • firstColumn 내보낼 첫 번째 셀의 열 번호입니다.
  • options ImportTableOptions 개체.

ImportTableOptions 매개변수는 데이터를 셀로 내보내기 위한 여러 옵션을 제공합니다. 그 중 일부는 다음과 같습니다.

  • CheckMergedCells Excel 문서에 병합된 셀이 포함되어 있습니까?
  • ColumnIndexes 데이터 원본에서 내보낼 열 인덱스(0부터 시작)의 정수 배열입니다. null은 모든 열을 내보내야 함을 의미합니다.
  • ConvertGridStyle 그리드 보기의 스타일을 셀에 적용할지 여부를 나타냅니다.
  • ConvertNumericData 문자열 값을 숫자 또는 날짜 값으로 변환해야 하는지 여부를 나타내는 부울 값입니다.
  • DateFormat 내보낸 DateTime 값이 있는 셀의 날짜 형식 문자열을 가져오거나 설정합니다.
  • DefaultValues 테이블의 셀에 대한 기본값은 null입니다.
  • InsertRows 데이터 레코드 내보내기를 위해 새 행을 추가해야 하는지 여부를 나타냅니다.
  • IsFieldNameShown 필드 이름을 내보내야 하는지 여부를 나타냅니다.
  • IsFormulas 데이터가 수식인지 여부를 나타냅니다.
  • IsHtmlString 데이터에 HTML 태그가 포함되어 있는지 여부를 나타냅니다. 값을 true로 설정하면 데이터를 Excel 문서로 내보내는 동안 HTML 형식이 유지됩니다.
  • NumberFormats 숫자 형식을 가져오거나 설정합니다.
  • ShiftFirstRowDown 행을 삽입할 때 첫 번째 행을 아래로 이동해야 하는지 여부를 나타냅니다.
  • TotalColumns 데이터 원본에서 내보낼 총 열 수를 가져오거나 설정합니다. -1은 주어진 데이터 소스의 모든 열을 의미합니다.
  • TotalRows 데이터 원본에서 내보낼 총 행 수를 가져오거나 설정합니다. -1은 주어진 데이터 소스의 모든 행을 의미합니다.

다음 예에서는 개체 컬렉션의 데이터를 병합된 셀이 포함된 워크시트로 내보내고 있습니다. Excel 문서에 병합된 셀이 포함되어 있으므로 ImportTableOptions.CheckMergedCells 속성 값을 true로 설정합니다.

// Opening an existing Workbook.
Workbook workbook = new Workbook("SampleMergedTemplate.xlsx");
List<Product> productList = new List<Product>();

// Creating a collection of Products
for (int i = 0; i < 3; i++)
{
    Product product = new Product
    {
        ProductId = i,
        ProductName = "Test Product - " + i
    };
    productList.Add(product);
}

ImportTableOptions tableOptions = new ImportTableOptions();
// Set CheckMergedCells property to true
tableOptions.CheckMergedCells = true;
tableOptions.IsFieldNameShown = false;

//Export data to excel template (in second row, first column) 
workbook.Worksheets[0].Cells.ImportCustomObjects((ICollection)productList, 1, 0, tableOptions);
workbook.Save("SampleMergedTemplate_out.xlsx", SaveFormat.Xlsx);

public class Product
{
    public int ProductId { get; set; }

    public string ProductName { get; set; }
}
개체 컬렉션의 데이터를 병합된 셀이 포함된 워크시트로 내보내기

병합된 셀이 포함된 Excel 문서로 데이터 내보내기

C#에서 한 Excel 파일의 행과 열을 다른 파일로 복사합니다.

한 Excel 문서에서 다른 Excel 문서로 행과 열을 프로그래밍 방식으로 복사할 수 있습니다. 행(또는 열)이 복사되면 업데이트된 참조가 있는 수식을 포함하여 행(또는 열)에 포함된 데이터와 값, 주석, 서식, 숨겨진 셀, 이미지 및 기타 그리기 개체도 복사됩니다. 동일한 워크시트 내에서 또는 Excel 문서의 다른 워크시트에서 행과 열을 복사할 수도 있습니다. Aspose.Cells는 행과 열을 복사하는 다음과 같은 방법을 제공합니다.

다음 예제 코드는 C#에서 한 Excel 문서에서 다른 문서로 행을 복사하는 방법을 보여줍니다.

// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");

// Instantiate the destination excel file.
Workbook destWorkbook = new Workbook();

// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];

// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];

// Copy all the rows of the first worksheet of source Workbook to
// the first worksheet of destination Workbook.
desWorksheet.Cells.CopyRows(srcWorksheet.Cells, 0, 0, srcWorksheet.Cells.MaxDisplayRange.RowCount);

// Save the excel file.
destWorkbook.Save("Destination_Workbook.xlsx");

다음 예제 코드는 한 Excel 문서의 특정 행을 다른 문서로 복사하는 방법을 보여줍니다.

// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");

// Instantiate the destination excel file.
Workbook destWorkbook = new Workbook();

// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];

// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];

// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);

// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);

// Save the excel file.
destWorkbook.Save("Destination_Workbook.xlsx");
한 Excel 문서에서 다른 Excel 문서로 행 데이터 복사

CopyColumn 또는 CopyColumns 메서드를 사용하여 한 Microsoft Excel 문서에서 다른 문서로 열의 데이터를 유사하게 복사할 수 있습니다.

C#에서 DataTable을 Excel로 내보내기

DataTable, DataColumnDataView와 같은 ADO.NET 개체의 데이터를 Excel 워크시트로 내보낼 수 있습니다. DataTable에서 데이터를 내보내려면 Cell 컬렉션의 ImportData 메서드를 호출합니다. ImportData 메서드에는 오버로드된 버전이 많이 있지만 다음을 사용합니다.

public int ImportData(
	DataTable table,
	int firstRow,
	int firstColumn,
	ImportTableOptions options
)

매개변수에 대한 설명은 다음과 같습니다.

  • 내보낼 테이블 DataTable 개체입니다.
  • firstRow 내보낼 첫 번째 셀의 행 번호입니다.
  • firstColumn 내보낼 첫 번째 셀의 열 번호입니다.
  • optionsType ImportTableOptions 개체.

다음 코드 샘플에서는 3개의 열과 2개의 행이 있는 DataTable 개체를 만들고 있습니다. 그리고 그것을 엑셀 워크시트로 내보냅니다.

// 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(int));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(int));

// 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);

// Setting IsFieldNameShown property to true will add column names // of the DataTable to the worksheet as a header row
ImportTableOptions tableOptions = new ImportTableOptions();
tableOptions.IsFieldNameShown = true;

// Exporting the contents of DataTable at the first row and first column.
worksheet.Cells.ImportData(dataTable, 0, 0, tableOptions);

// Saving the Excel file
workbook.Save("DataTable_Eport.xlsx");
Excel로 DataTable 내보내기

Excel로 DataTable 내보내기

C#에서 선택 DataColumn의 데이터를 Excel로 내보내기

DataTable 또는 DataView의 선택적 DataColumns를 Excel 문서로 내보낼 수 있습니다. 앞에서 설명한 것처럼 ImportData 메서드는 ImportTableOptions 유형의 인수를 허용합니다. ImportTableOptions 클래스에는 내보내려는 열 인덱스(0부터 시작)의 배열을 허용하는 ColumnIndexes 속성이 있습니다. 다음 코드 샘플에서는 DataTable의 두 DataColumn만 Excel 워크시트로 내보내고 있습니다.

// Instantiating a "Products" DataTable object
DataTable dataTable = new DataTable("Products");

// Adding columns to the DataTable object
dataTable.Columns.Add("Product ID", typeof(int));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(int));

// 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 export options
ImportTableOptions importOptions = new ImportTableOptions();
// Sets the columns (0-based) to export from data source.
// null means all columns should be exported.
importOptions.ColumnIndexes = new int[] { 0, 1 };
importOptions.IsFieldNameShown = true;

// Exporting the values of 1st and 2nd columns of the data table
sheet.Cells.ImportData(dataTable, 0, 0, importOptions);

book.Save("DataColumsExport.xlsx");
선택 DataColumn의 데이터를 Excel로 내보내기

DataColumns를 Excel로 출력

C#의 DataView에서 Excel로 데이터 내보내기

DataView는 DataTable의 데이터 하위 집합을 표시하도록 사용자 지정할 수 있는 DataTable의 보기입니다. 다음과 같은 오버로드된 버전의 ImportData 메서드를 사용하여 DataView에서 Excel 문서로 데이터를 내보냅니다.

public int ImportData(
	DataView dataView,
	int firstRow,
	int firstColumn,
	ImportTableOptions options
)

DataView를 만드는 방법에는 두 가지가 있습니다. DataView 생성자를 사용하거나 DataTableDefaultView 속성에 대한 참조를 만들 수 있습니다. 다음 코드 샘플에서는 나중에 DataView를 만드는 방법을 사용합니다.

worksheet.Cells.ImportData(dataTable.DefaultView, 0, 0, options);

C#의 DataGrid 및 GridView에서 Excel로 데이터 내보내기

Aspose.Cells 라이브러리를 사용하면 DataGrid 및 GridView와 같은 Microsoft Grid 컨트롤에서 Excel 워크시트로 데이터를 내보낼 수 있습니다. DataGrid에서 데이터를 내보내는 ImportDataGrid 메서드와 GridView에서 데이터를 내보내는 ImportGridView 메서드를 제공합니다.

ImportDataGrid 메서드의 오버로드된 버전이 많이 있지만 일반적인 오버로드는 다음 매개 변수를 사용합니다.

  • dataGrid, 콘텐츠를 내보내는 DataGrid 개체입니다.
  • firstRow, 데이터를 내보낼 첫 번째 셀의 행 번호.
  • firstColumn 데이터를 내보낼 첫 번째 셀의 열 번호입니다.
  • insertRows, 데이터에 맞추기 위해 워크시트에 추가 행을 추가해야 하는지 여부를 나타내는 부울 속성입니다.
  • importStyle, 셀 스타일을 내보내야 하는지 여부를 나타내는 부울 속성.

다음 코드 예제에서는 DataGrid에서 C#의 Excel 파일로 데이터를 내보내는 방법을 보여줍니다.

// Create a DataTable object and set it as the DataSource of the DataGrid.
DataTable dataTable = new DataTable("Products");
dataTable.Columns.Add("Product ID", typeof(int));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(int));

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
DataGrid dg = new DataGrid();
dg.DataSource = dataTable;
dg.DataBind();

// We have a DataGrid object with some data in it.
// Lets export it to an Excel worksheet.

// Creat a new workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];

// Exporting the contents of the DataGrid to the worksheet
worksheet.Cells.ImportDataGrid(dg, 0, 0, false);

// Save it as Excel file
workbook.Save("ExportDataGrid.xlsx");

C#에서 HTML 형식의 데이터를 Excel로 내보내기

Aspose.Cells를 사용하면 HTML 형식의 데이터를 Excel 워크시트로 내보낼 수 있습니다. API는 데이터를 내보내는 동안 HTML 형식의 텍스트를 구문 분석하고 HTML을 형식이 지정된 셀 값으로 변환합니다. 다음 샘플 코드에서 DataTable에는 HTML 형식의 텍스트가 포함되어 있으며 ImportData 메서드를 사용하여 Excel 문서로 내보내고 있습니다.

// Prepare a DataTable with some HTML formatted values
DataTable dataTable = new DataTable("Products");

dataTable.Columns.Add("Product ID", typeof(int));
dataTable.Columns.Add("Product Name", typeof(string));
dataTable.Columns.Add("Units In Stock", typeof(int));

DataRow dr = dataTable.NewRow();
dr[0] = 1;
// Make text italicize
dr[1] = "<i>Aniseed</i> Syrup";
dr[2] = 15;
dataTable.Rows.Add(dr);

dr = dataTable.NewRow();
dr[0] = 2;
// Make text bold
dr[1] = "<b>Boston Crab Meat</b>";
dr[2] = 123;
dataTable.Rows.Add(dr);

// Create export options
ImportTableOptions exportOptions = new ImportTableOptions();
exportOptions.IsFieldNameShown = true;
// Set IsHtmlString property to true as the data contains HTML tags. 
exportOptions.IsHtmlString = true;

// Create workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];

worksheet.Cells.ImportData(dataTable, 0, 0, exportOptions);

workbook.Save("HTMLFormattedData_Out.xlsx");
HTML 형식의 데이터를 스프레드시트로

HTML 내보낸 데이터를 Excel 문서로 출력

C#에서 HTML 파일을 Excel로 내보내기

Aspose.Cells를 사용하면 HTML 파일을 Excel로 내보낼 수 있습니다. HTML 파일은 Microsoft Excel 지향적이어야 합니다. 즉, MS-Excel에서 열 수 있어야 합니다.

// An HTML file
string filePath = "Book1.html";

// Instantiate LoadOptions specified by the LoadFormat.
HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html);

// Create a Workbook object and open the HTML file.
Workbook wb = new Workbook(filePath, loadOptions);

// Save the file as Excel Document
wb.Save("Book1_out.xlsx");

JSON 데이터를 C#에서 Excel로 내보내기

때로는 JSON 데이터를 Excel 문서로 내보낼 필요가 있습니다. Aspose.Cell을 사용하면 몇 줄의 코드로 이 작업을 쉽게 수행할 수 있습니다. Aspose.Cells는 JSON 데이터를 Excel 문서로 내보내기 위한 ImportData 메서드가 있는 JsonUtility 클래스를 제공합니다. ImportData 메서드는 JsonLayoutOptions 객체를 매개변수로 받습니다. JsonLayoutOptions 클래스는 JSON 레이아웃의 옵션을 나타내며 다음과 같은 속성을 갖는다.

  • ArrayAsTable: Indicates whether the array should be processed as a table.
  • ConvertNumericOrDate: Gets or sets a value that indicates whether the string in JSON is to be converted to numeric or date.
  • DateFormat: Gets and sets the format of the date value.
  • IgnoreArrayTitle: Indicates whether to ignore the title if the property of the object is an array.
  • IgnoreNull: Indicates whether the null value should be ignored.
  • IgnoreObjectTitle: Indicates whether to ignore the title if the property of the object is an object.
  • NumberFormat: Gets and sets the format of the numeric value.
  • TitleStyle: Gets and sets the style of the title.

다음 예제 코드에서는 JSON 데이터를 C#의 Excel 파일로 내보내고 있습니다.

// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];

// Read JSON file
string jsonInput = File.ReadAllText("Sample.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;

// Export JSON Data
JsonUtility.ImportData(jsonInput, worksheet.Cells, 0, 0, options);

// Save Excel file
workbook.Save("ExportingJsonData.xlsx");
{
  "quiz": {
    "sport": {
      "q1": {
        "question": "Which one is correct team name in NBA?",
        "answer": "Huston Rocket"
      }
    },
    "maths": {
      "q1": {
        "question": "5 + 7 = ?",
        "answer": "12"
      },
      "q2": {
        "question": "12 - 8 = ?",
        "answer": "4"
      }
    }
  }
}
JSON 데이터를 Excel 문서로

JSON 데이터를 Excel로 내보내기

CSV 데이터를 C#에서 Excel로 내보내기

CSV(쉼표로 구분된 값) 파일은 쉼표를 사용하여 값을 구분하는 구분된 텍스트 파일입니다. CSV 파일은 일반적으로 표 형식 데이터(숫자 및 텍스트)를 일반 텍스트로 저장하며, 이 경우 각 행에 동일한 수의 필드가 있습니다.

다음 코드 샘플은 Aspose.Cells 라이브러리를 사용하여 CSV 파일을 열고 Excel 파일로 저장하는 방법을 보여줍니다.

// Instantiate LoadOptions with CSV LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV);

// Open CSV file as a Workbook object
Workbook wb = new Workbook("Business-Price.csv", loadOptions);

// Save the file as an Excel Documnt
wb.Save("CSVAsAnExcelDocument.xlsx");
스프레드시트 문서에서 CSV 파일 열기

CSV를 Excel 문서로

결론

이 게시물에서는 Array, DataTable, DataView, DataGrid 및 GridView에서 C#의 Excel로 데이터를 얼마나 쉽게 내보낼 수 있는지 살펴보았습니다. HTML, JSON, CSV 데이터를 Excel 워크시트로 내보내는 방법도 살펴보았습니다. Aspose.Cells API가 제공하는 이러한 기능과 기타 여러 기능에 대해 자세히 알아보려면 문서를 확인하십시오. 질문이 있으시면 지원 포럼을 통해 문의해 주십시오.

또한보십시오