使用C#将数据导出为excel
时间: 2024-05-16 18:14:14 浏览: 162
C#导出数据到excel
4星 · 用户满意度95%
要使用C#将数据导出为Excel,可以使用Microsoft.Office.Interop.Excel库。
首先,需要在项目中添加对Microsoft.Office.Interop.Excel库的引用。然后,可以按照以下步骤进行操作:
1. 创建一个Excel应用程序对象
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
```
2. 创建一个Workbook对象
```csharp
Excel.Workbook workbook = excelApp.Workbooks.Add();
```
3. 创建一个Worksheet对象,并设置它的名称
```csharp
Excel.Worksheet worksheet = workbook.ActiveSheet;
worksheet.Name = "MySheet";
```
4. 将数据写入Worksheet对象
```csharp
// 假设数据已经存储在一个二维数组中
object[,] data = new object[,] { { "Name", "Age" }, { "John", 25 }, { "Jane", 30 } };
// 将数据写入Worksheet对象
int rowCount = data.GetLength(0);
int columnCount = data.GetLength(1);
for (int row = 1; row <= rowCount; row++)
{
for (int column = 1; column <= columnCount; column++)
{
worksheet.Cells[row, column] = data[row-1, column-1];
}
}
```
5. 可以设置Worksheet对象的格式,如对齐方式、字体、颜色等。
6. 最后,将Workbook对象保存为Excel文件
```csharp
// 将Workbook对象保存为Excel文件
string filePath = "C:\\MyExcelFile.xlsx";
workbook.SaveAs(filePath);
// 关闭Excel应用程序对象
excelApp.Quit();
```
完整的代码示例:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
worksheet.Name = "MySheet";
object[,] data = new object[,] { { "Name", "Age" }, { "John", 25 }, { "Jane", 30 } };
int rowCount = data.GetLength(0);
int columnCount = data.GetLength(1);
for (int row = 1; row <= rowCount; row++)
{
for (int column = 1; column <= columnCount; column++)
{
worksheet.Cells[row, column] = data[row-1, column-1];
}
}
// 设置Worksheet对象的格式
worksheet.Range["A1:B1"].Font.Bold = true;
worksheet.Range["A1:B1"].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
worksheet.Range["A2:A3"].HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
// 将Workbook对象保存为Excel文件
string filePath = "C:\\MyExcelFile.xlsx";
workbook.SaveAs(filePath);
excelApp.Quit();
```
阅读全文