C#Excel 파일 만들기 자습서
개술
C에서 Excel 파일을 생성하는 방법
IronXL 에서 C#Excel 파일을 생성합니다.그물
IronXL is an intuitive C# & VB Excel API Excel 스프레드시트 파일을 읽기, 편집 및 작성할 수 있습니다.NET는 번개 같은 성능을 제공합니다.MS Office 또는 Excel InterOp을 설치할 필요가 없습니다.
IronXL은 완벽하게 지원됩니다.네트워크 코어.NET 프레임워크, Xamarin, Mobile, Linux, MacOS 및 Azure.
IronXL 기능:
https://www.nuget.org/packages/IronXL.Excel/
또는 IronXL.Dll can be downloaded 및 를 프로젝트에 추가합니다.
C#:
/**
Create & Save Excel File
anchor-create-and-save-an-excel-file
**/
using IronXL;
//default file format is XLSX, we can override it using CreatingOptions
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var sheet = workbook.CreateWorkSheet("example_sheet");
sheet["A1"].Value = "Example";
//set value to multiple cells
sheet["A2:A4"].Value = 5;
sheet["A5"].Style.SetBackgroundColor("#f0f0f0");
//set style to multiple cells
sheet["A5:A6"].Style.Font.Bold = true;
//set formula
sheet["A6"].Value = "=SUM(A2:A4)";
if (sheet["A6"].IntValue == sheet["A2:A4"].IntValue)
{
Console.WriteLine("Basic test passed");
}
workbook.SaveAs("example_workbook.xlsx");
VB:'''
'''Create & Save Excel File
'''anchor-create-and-save-an-excel-file
'''*
Imports IronXL
'default file format is XLSX, we can override it using CreatingOptions
Private workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Private sheet = workbook.CreateWorkSheet("example_sheet")
Private sheet("A1").Value = "Example"
'set value to multiple cells
Private sheet("A2:A4").Value = 5
sheet("A5").Style.SetBackgroundColor("#f0f0f0")
'set style to multiple cells
sheet("A5:A6").Style.Font.Bold = True
'set formula
sheet("A6").Value = "=SUM(A2:A4)"
If sheet("A6").IntValue = sheet("A2:A4").IntValue Then
Console.WriteLine("Basic test passed")
End If
workbook.SaveAs("example_workbook.xlsx")
첫걸음1. 무료 IronXL C# 라이브러리 다운로드
NuGet을 사용하여 설치
IronXL NuGet 패키지를 설치하는 방법에는 세 가지가 있습니다.
Visual Studio
VisualStudio는 프로젝트에 NuGet 패키지를 설치할 수 있는 NuGet 패키지 관리자를 제공합니다."프로젝트"메뉴나 "해결 방안 자원 관리자"에서 항목을 오른쪽 단추로 눌러서 접근할 수 있습니다.아래의 그림 3과 그림 4는 이 두 가지 옵션을 보여 준다.
그림 3 – 프로젝트 메뉴
그림 4 – 솔루션 리소스 매니저를 마우스 오른쪽 버튼으로 클릭
옵션 중 하나에서 Manage NuGet Packages를 클릭한 후 IronXL을 탐색합니다.그림 5와 같이 Excel 패키지를 설치합니다.
그림 5 – IronXL을 설치합니다.Excel NuGet 패키지
개발자 명령 프롬프트
개발자 명령 프롬프트를 열고 다음 절차에 따라 IronXL을 설치합니다.Excel NuGet 패키지:
NuGet 패키지 직접 다운로드
NuGet 패키지를 다운로드하려면 다음 절차를 따르십시오.
라이브러리를 직접 다운로드하여 IronXL 설치
IronXL을 설치하는 두 번째 방법은 다음 URL에서 직접 다운로드하는 것입니다. https://ironsoftware.com/csharp/excel/
그림 6 – IronXL 라이브러리 다운로드
다음 절차에 따라 항목의 라이브러리를 참조합니다.
가자!
지금 당신은 이미 설정이 되어 있습니다. 우리는 IronXL 라이브러리의 하이라이트 기능을 사용할 수 있습니다!
어떻게 강좌를 읽습니까
2. ASP를 만듭니다.그물
그림 1 - 새 항목
ironsoftware.com/csharp/excel/
그림 2 – 웹 양식
3. Excel 워크북 만들기
IronXL을 사용하여 새로운 Excel 워크북을 만드는 것은 더 이상 간단할 수 없습니다!이것은 한 줄의 코드다!예, 정말:
C#:
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
VB:Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
IronXL을 사용하여 XLS(이전 Excel 파일 버전) 및 XLSX(현재 및 업데이트된 파일 버전) 파일 형식을 작성할 수 있습니다.3.1. 기본 워크시트 설정
그리고 기본 워크시트를 만드는 것이 더 간단합니다
C#:
var sheet = workbook.CreateWorkSheet("2020 Budget");
VB:Dim sheet = workbook.CreateWorkSheet("2020 Budget")
위 코드 세그먼트의 "Sheet"은 워크시트를 표시합니다. 워크시트를 사용하면 셀 값을 설정할 수 있고, Excel이 할 수 있는 거의 모든 일을 할 수 있습니다.워크북과 워크시트 사이의 차이에 대해 곤혹스러우시다면, 제가 설명해 드리겠습니다.
작업장에는 작업표가 포함되어 있다.이것은 워크북에 임의의 워크시트를 추가할 수 있음을 의미합니다.뒷글에서 나는 어떻게 이 점을 해냈는지 설명할 것이다.워크시트는 행과 열을 포함합니다.행과 열이 교차하는 것을 셀이라고 하는데 이것은 Excel을 사용할 때 처리할 내용입니다.
4. 셀 값 설정
4.1. 셀 값을 수동으로 설정합니다.
셀 값을 수동으로 설정하려면 다음 예와 같이 사용 중인 셀을 표시하고 값을 설정합니다.
C#:
/**
Set Cell Value Manually
anchor-set-cell-values
**/
sheet["A1"].Value = "January";
sheet["B1"].Value = "February";
sheet["C1"].Value = "March";
sheet["D1"].Value = "April";
sheet["E1"].Value = "May";
sheet["F1"].Value = "June";
sheet["G1"].Value = "July";
sheet["H1"].Value = "August";
sheet["I1"].Value = "September";
sheet["J1"].Value = "October";
sheet["K1"].Value = "November";
sheet["L1"].Value = "December";
VB:'''
'''Set Cell Value Manually
'''anchor-set-cell-values
'''*
sheet("A1").Value = "January"
sheet("B1").Value = "February"
sheet("C1").Value = "March"
sheet("D1").Value = "April"
sheet("E1").Value = "May"
sheet("F1").Value = "June"
sheet("G1").Value = "July"
sheet("H1").Value = "August"
sheet("I1").Value = "September"
sheet("J1").Value = "October"
sheet("K1").Value = "November"
sheet("L1").Value = "December"
여기서 나는 A부터 L열까지 채워 넣었는데, 각 열의 첫 줄은 모두 달의 이름이 다르다.4.2. 동적 셀 값 설정
동적 설정 값은 거의 앞의 코드 세그먼트와 유사합니다.이렇게 하는 장점은 네가 단원격의 위치를 억지로 인코딩할 필요가 없다는 것이다.다음 코드 예시에서, 새로운 무작위 대상을 만들어서 무작위 수를 만들고, for 순환을 사용하여 충전하고자 하는 칸 범위 내에서 교체합니다.
C#:
/**
Set Cell Value Dynamically
anchor-set-cell-values-dynamically
**/
Random r = new Random();
for (int i = 2; i <= 11; i++)
{
sheet["A" + i].Value = r.Next(1, 1000);
sheet["B" + i].Value = r.Next(1000, 2000);
sheet["C" + i].Value = r.Next(2000, 3000);
sheet["D" + i].Value = r.Next(3000, 4000);
sheet["E" + i].Value = r.Next(4000, 5000);
sheet["F" + i].Value = r.Next(5000, 6000);
sheet["G" + i].Value = r.Next(6000, 7000);
sheet["H" + i].Value = r.Next(7000, 8000);
sheet["I" + i].Value = r.Next(8000, 9000);
sheet["J" + i].Value = r.Next(9000, 10000);
sheet["K" + i].Value = r.Next(10000, 11000);
sheet["L" + i].Value = r.Next(11000, 12000);
}
VB:'''
'''Set Cell Value Dynamically
'''anchor-set-cell-values-dynamically
'''*
Dim r As New Random()
For i As Integer = 2 To 11
sheet("A" & i).Value = r.Next(1, 1000)
sheet("B" & i).Value = r.Next(1000, 2000)
sheet("C" & i).Value = r.Next(2000, 3000)
sheet("D" & i).Value = r.Next(3000, 4000)
sheet("E" & i).Value = r.Next(4000, 5000)
sheet("F" & i).Value = r.Next(5000, 6000)
sheet("G" & i).Value = r.Next(6000, 7000)
sheet("H" & i).Value = r.Next(7000, 8000)
sheet("I" & i).Value = r.Next(8000, 9000)
sheet("J" & i).Value = r.Next(9000, 10000)
sheet("K" & i).Value = r.Next(10000, 11000)
sheet("L" & i).Value = r.Next(11000, 12000)
Next i
A2에서 L11까지의 각 셀에는 임의로 생성된 고유한 값이 있습니다.동적 값에 대해 말하자면 어떻게 데이터베이스에서 단원격에 데이터를 직접 동적으로 추가하는지 배우는 것이 어떻습니까?다음 코드 세션은 데이터베이스 연결을 정확하게 설정했다고 가정하면 어떻게 완성되었는지 신속하게 보여 줍니다.
4.3. 데이터베이스에서 직접 추가
C#:
/**
Add Cells from Database
anchor-add-directly-from-a-database
**/
//Create database objects to populate data from database
string contring;
string sql;
DataSet ds = new DataSet("DataSetName");
SqlConnection con;
SqlDataAdapter da;
//Set Database Connection string
contring = @"Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password";
//SQL Query to obtain data
sql = "SELECT Field_Names FROM Table_Name";
//Open Connection & Fill DataSet
con = new SqlConnection(contring);
da = new SqlDataAdapter(sql, con);
con.Open();
da.Fill(ds);
//Loop through contents of dataset
foreach (DataTable table in ds.Tables)
{
int Count = table.Rows.Count - 1;
for (int j = 12; j <= 21; j++)
{
sheet["A" + j].Value = table.Rows[Count]["Field_Name_1"].ToString();
sheet["B" + j].Value = table.Rows[Count]["Field_Name_2"].ToString();
sheet["C" + j].Value = table.Rows[Count]["Field_Name_3"].ToString();
sheet["D" + j].Value = table.Rows[Count]["Field_Name_4"].ToString();
sheet["E" + j].Value = table.Rows[Count]["Field_Name_5"].ToString();
sheet["F" + j].Value = table.Rows[Count]["Field_Name_6"].ToString();
sheet["G" + j].Value = table.Rows[Count]["Field_Name_7"].ToString();
sheet["H" + j].Value = table.Rows[Count]["Field_Name_8"].ToString();
sheet["I" + j].Value = table.Rows[Count]["Field_Name_9"].ToString();
sheet["J" + j].Value = table.Rows[Count]["Field_Name_10"].ToString();
sheet["K" + j].Value = table.Rows[Count]["Field_Name_11"].ToString();
sheet["L" + j].Value = table.Rows[Count]["Field_Name_12"].ToString();
}
Count++;
}
VB:'''
'''Add Cells from Database
'''anchor-add-directly-from-a-database
'''*
'Create database objects to populate data from database
Dim contring As String
Dim sql As String
Dim ds As New DataSet("DataSetName")
Dim con As SqlConnection
Dim da As SqlDataAdapter
'Set Database Connection string
contring = "Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password"
'SQL Query to obtain data
sql = "SELECT Field_Names FROM Table_Name"
'Open Connection & Fill DataSet
con = New SqlConnection(contring)
da = New SqlDataAdapter(sql, con)
con.Open()
da.Fill(ds)
'Loop through contents of dataset
For Each table As DataTable In ds.Tables
Dim Count As Integer = table.Rows.Count - 1
For j As Integer = 12 To 21
sheet("A" & j).Value = table.Rows(Count)("Field_Name_1").ToString()
sheet("B" & j).Value = table.Rows(Count)("Field_Name_2").ToString()
sheet("C" & j).Value = table.Rows(Count)("Field_Name_3").ToString()
sheet("D" & j).Value = table.Rows(Count)("Field_Name_4").ToString()
sheet("E" & j).Value = table.Rows(Count)("Field_Name_5").ToString()
sheet("F" & j).Value = table.Rows(Count)("Field_Name_6").ToString()
sheet("G" & j).Value = table.Rows(Count)("Field_Name_7").ToString()
sheet("H" & j).Value = table.Rows(Count)("Field_Name_8").ToString()
sheet("I" & j).Value = table.Rows(Count)("Field_Name_9").ToString()
sheet("J" & j).Value = table.Rows(Count)("Field_Name_10").ToString()
sheet("K" & j).Value = table.Rows(Count)("Field_Name_11").ToString()
sheet("L" & j).Value = table.Rows(Count)("Field_Name_12").ToString()
Next j
Count += 1
Next table
특정 셀의 Value 속성을 입력할 셀의 필드 이름으로 설정하기만 하면 됩니다.5. 서식 적용
5.1. 셀의 배경색 설정하기
셀이나 일련의 셀의 배경색을 설정하려면 다음 그림과 같이 코드 한 줄만 있으면 됩니다.
C#:
/**
Set Cell Background Color
anchor-set-background-colors-of-cells
**/
sheet["A1:L1"].Style.SetBackgroundColor("#d3d3d3");
VB:'''
'''Set Cell Background Color
'''anchor-set-background-colors-of-cells
'''*
sheet("A1:L1").Style.SetBackgroundColor("#d3d3d3")
그러면 셀 범위의 배경색이 회색으로 설정됩니다.색상은 RGB(빨간색, 녹색, 파란색) 형식으로 앞의 두 문자는 빨간색, 뒤의 두 문자는 녹색, 마지막 두 문자는 파란색을 나타낸다.숫자 범위는 0에서 9까지이고 A에서 F(16진수)까지입니다.5.2. 경계 생성하기
IronXL을 사용하여 다음과 같이 프레임을 쉽게 만들 수 있습니다.
C#:
/**
Create Borders
anchor-create-borders
**/
sheet["A1:L1"].Style.TopBorder.SetColor("#000000");
sheet["A1:L1"].Style.BottomBorder.SetColor("#000000");
sheet["L2:L11"].Style.RightBorder.SetColor("#000000");
sheet["L2:L11"].Style.RightBorder.Type = IronXL.Styles.BorderType.Medium;
sheet["A11:L11"].Style.BottomBorder.SetColor("#000000");
sheet["A11:L11"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium;
VB:'''
'''Create Borders
'''anchor-create-borders
'''*
sheet("A1:L1").Style.TopBorder.SetColor("#000000")
sheet("A1:L1").Style.BottomBorder.SetColor("#000000")
sheet("L2:L11").Style.RightBorder.SetColor("#000000")
sheet("L2:L11").Style.RightBorder.Type = IronXL.Styles.BorderType.Medium
sheet("A11:L11").Style.BottomBorder.SetColor("#000000")
sheet("A11:L11").Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium
위 코드에서 나는 검은색의 맨 윗부분과 밑에 있는 테두리를 셀 A1에서 L1로 설정한 다음에 오른쪽 테두리를 셀 L2에서 L11로 설정하고 테두리의 스타일을'중'으로 설정한다.마지막으로, 나는 단원격 A11에서 L11까지 아래 테두리를 설정했다C#:
/**
Use Formulas in Cells
anchor-use-formulas-in-cells
**/
decimal sum = sheet["A2:A11"].Sum();
decimal avg = sheet["B2:B11"].Avg();
decimal max = sheet["C2:C11"].Max();
decimal min = sheet["D2:D11"].Min();
sheet["A12"].Value = sum;
sheet["B12"].Value = avg;
sheet["C12"].Value = max;
sheet["D12"].Value = min;
VB:'''
'''Use Formulas in Cells
'''anchor-use-formulas-in-cells
'''*
Dim sum As Decimal = sheet("A2:A11").Sum()
Dim avg As Decimal = sheet("B2:B11").Avg()
Dim max As Decimal = sheet("C2:C11").Max()
Dim min As Decimal = sheet("D2:D11").Min()
sheet("A12").Value = sum
sheet("B12").Value = avg
sheet("C12").Value = max
sheet("D12").Value = min
이렇게 하면 단원격의 데이터 형식을 설정하여 공식적인 결과를 얻을 수 있다는 장점이 있다.위의 코드는 SUM(구화값), AVG(평균값), MAX(최고값 획득)와 MIN(최저값 획득) 공식을 어떻게 사용하는지 보여 준다.7.1. 워크시트 속성 설정
워크시트 속성은 행과 열을 동결하고 암호를 사용하여 워크시트를 보호하는 것을 포함한다.다음과 같이 표시됩니다.
C#:
/**
Set Worksheet Properties
anchor-set-worksheet-and-print-properties
**/
sheet.ProtectSheet("Password");
sheet.CreateFreezePane(0, 1);
VB:'''
'''Set Worksheet Properties
'''anchor-set-worksheet-and-print-properties
'''*
sheet.ProtectSheet("Password")
sheet.CreateFreezePane(0, 1)
첫 번째 줄이 동결되어 작업표의 나머지 부분과 함께 굴러가지 않습니다.워크시트는 암호를 통해 편집되지 않고 보호할 수 있다.그림 7과 8은 이 점을 보여 준다.그림 7 – 창 고정
그림 8 – 보호 워크시트
7.2. 페이지 및 인쇄 속성 설정
페이지 방향, 페이지 크기, 인쇄 영역 등과 같은 페이지 속성을 설정할 수 있습니다.
C#:
/**
Page & Print Properties
anchor-set-page-and-print-properties
**/
sheet.SetPrintArea("A1:L12");
sheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape;
sheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4;
VB:'''
'''Page & Print Properties
'''anchor-set-page-and-print-properties
'''*
sheet.SetPrintArea("A1:L12")
sheet.PrintSetup.PrintOrientation = IronXL.Printing.PrintOrientation.Landscape
sheet.PrintSetup.PaperSize = IronXL.Printing.PaperSize.A4
인쇄 영역은 A1에서 L12로 설정됩니다.방향은 가로, 용지 크기는 A4로 설정합니다.그림 9 – 인쇄 설정
8. 작업장 보관
워크북을 저장하려면 다음 코드를 사용합니다.
C#:
/**
Save Workbook
anchor-save-workbook
**/
workbook.SaveAs("Budget.xlsx");
VB:'''
'''Save Workbook
'''anchor-save-workbook
'''*
workbook.SaveAs("Budget.xlsx")
Reference
이 문제에 관하여(C#Excel 파일 만들기 자습서), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/ironsoftware/c-create-excel-file-tutorial-577l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)