在 C#中如何把数据写入 Excel?
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using ExcelApplication = Microsoft.Office.Interop.Excel.ApplicationClass;
namespace ExcalDemo
...{
public class ExcelFiles
...{
public void CreateExcelFiles()
...{
//创建一个 Excel 实例
ExcelApplication excel = new ExcelApplication();
try
...{
// 注释掉的语句是:从磁盘指定位置打开一个 Excel 文件
//excel.Workbooks.Open("demo.xls", Missing.Value, Missing.Value,
//Missing.Value,Missing.Value, Missing.Value, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value, Missing.Value);
excel.Visible = false;// 不显示 Excel 文件,如果为 true 则显示 Excel 文件
excel.Workbooks.Add(Missing.Value);// 添加工作簿
Worksheet sheet = (Worksheet)excel.ActiveSheet;// 获取当前工作表
Range range = null;// 创建一个空的单元格对象
sheet.get_Range(sheet.Cells[29,2],sheet.Cells[29,2]).Orientation=Excel.Xl
Orientation.xlVertical;//字体竖直居中在单元格内
range = sheet.get_Range("A1", Missing.Value);// 获取单个单元格
range.RowHeight = 20; // 设置行高
range.ColumnWidth = 20; // 设置列宽
range.Borders.LineStyle = 1; // 设置单元格边框
range.Font.Bold = true; // 加粗字体
range.Font.Size = 20; // 设置字体大小
range.Font.ColorIndex = 5; // 设置字体颜色
range.Interior.ColorIndex = 6; // 设置单元格背景
range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 设置单元格水
平居中
range.VerticalAlignment = XlVAlign.xlVAlignCenter;// 设置单元格垂直