using Microsoft.Office.Interop.Excel;
using System;
using System.Reflection;
namespace ExcelDemo
{
class Program
{
static void Main(string[] args)
{
// 新建一个新的EXCEL文档
string newFile = @"E:\test.xlsx";
Application excel = new Application();
_Workbook myWorkbook; // 工作薄实例声明
_Worksheet myWorksheet; // 工作表实例声明
excel.Application.Workbooks.Add(true); // 不存在的相同文件,则建立一个新的文件
myWorkbook = excel.ActiveWorkbook; // 工作薄赋值为excel中的已激活工作薄
myWorksheet = (Microsoft.Office.Interop.Excel._Worksheet)myWorkbook.ActiveSheet; // 工作表赋值为工作簿中已激活的工作表
myWorksheet.Name = "测试一";
// 取得sheet
Sheets sh = myWorkbook.Sheets;
// 添加sheet,参数说明(之前,之后,数量,类型)
excel.Sheets.Add(Missing.Value, myWorksheet, 5, XlSheetType.xlWorksheet);
// 删除指定sheet
_Worksheet delSheet = sh.get_Item("Sheet6");
delSheet.Delete();
// 新添加Sheet重新命名,Sheet页面索引从1开始
for (int i = 1; i <= sh.Count; i++)
{
_Worksheet tempSheet = sh.get_Item(i);
if (!tempSheet.Name.Equals("测试一"))
{
tempSheet.Name = string.Format("新添加Sheet-{0}", i);
}
}
// 合并单元格(合并一行多列)
Range rg1 = myWorksheet.get_Range("A1", "F1");
rg1.MergeCells = true;
// 设置单元格文字
rg1.Cells[1, 1] = "合并单元格内容写入测试一";
// 设置单元格水平垂直居中
rg1.HorizontalAlignment = Microsoft.Office.Core.XlVAlign.xlVAlignCenter;
Range rg2 = myWorksheet.get_Range("H1", "W1");
rg2.MergeCells = true;
rg2.Cells[1, 1] = "合并单元格内容写入测试二";
rg2.HorizontalAlignment = Microsoft.Office.Core.XlVAlign.xlVAlignCenter;
// 合并单元格(合并一列多行)
Range rg3 = myWorksheet.get_Range("A4", "A9");
rg3.MergeCells = true;
rg3.Cells[1, 1] = "合并单元格内容写入测试三";
// 单元格宽度自适应
rg3.EntireColumn.AutoFit();
rg3.HorizontalAlignment = Microsoft.Office.Core.XlVAlign.xlVAlignCenter;
// 添加行和列
myWorksheet = sh.get_Item(1);
// 添加行
((Range)myWorksheet.Rows[2, Missing.Value]).Insert(Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
// 添加列
myWorksheet.Columns[7].Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
// 保存文件
//屏蔽掉系统跳出的Alert
excel.AlertBeforeOverwriting = false;
//保存到指定目录
myWorkbook.SaveAs(newFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
myWorkbook.Close(null, null, null);
excel.Quit();
excel = null;
Console.WriteLine("完成");
}
}
}
完善学习中,如有错误、不足之处,请都都包含,指正
C# Excel 操作
最新推荐文章于 2020-10-29 16:07:07 发布