using Microsoft.Office.Interop.Excel;//引用Microsoft.Office.Interop.Excel
//声明一个Excel Application
Microsoft.Office.Interop.Excel.Application appExcel = new Microsoft.Office.Interop.Excel.Application();
//声明一个Excel Workbook
Microsoft.Office.Interop.Excel.Workbook workbookData;
//声明一个Excel Work Sheet
Microsoft.Office.Interop.Excel.Worksheet worksheetData;
//打开路径为filepath的Excel
workbookData = appExcel.Workbooks.Open(filepath , System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
try
{
//不显示弹窗、警告。在后台写入Excel
appExcel.Visible = false;
appExcel.DisplayAlerts = false;
//获取所有Sheet、SheetName
int sheet = workbookData.Worksheets.Count;
string[] sheetName = new string[sheet];
for (int i = 0; i < sheet; i++)
{
worksheetData = (Worksheet)workbookData.Worksheets[i + 1];
sheetName[i] = worksheetData.Name;
}
//判断Sheet1$是否存在
int sheetExist = Array.IndexOf(sheetName, "Sheet1$");
if (sheetExist != -1)
{
//Sheet1$存在,则操作下一个Sheet
worksheetData = (Worksheet)workbookData.Worksheets[sheetExist + 1];
}
else
{
if (sheet == 1)
{
worksheetData = (Worksheet)workbookData.Worksheets[1];
//往Sheet1$ H列 11+i行写入数值,并格式化为Wingdings 2,即在Excel执行打勾操作
for (int i = 0; i < checkItem; i++)
{
worksheetData.Range["H" + (11 + i)].Value = "R";
worksheetData.Range["H" + (11 + i)].Characters.Font.Name = "Wingdings 2";
}
//worksheetData.Range["H11"].Value = "R";
//worksheetData.Range["H11"].Characters.Font.Name = "Wingdings 2";
}
else
{
worksheetData = (Worksheet)workbookData.Worksheets[sheet];
}
if (sheet < qty)
{
//新增Sheet,复制Sheet1内容到Sheet1后面
worksheetData.Copy(After: worksheetData);
}
}
worksheetData.Name = "Sheet 名字";
//往框内赋值,可先用Excel宏记录操作获得下列命令
worksheetData.Range["D4:F4"].Value = "值1";
worksheetData.Range["D5:F5"].Value = "值2";
worksheetData.Range["D7:F7"].Value = "值3";
worksheetData.Range["D8:F8"].Value = "值4";
workbookData.Save();
}
catch
{
MessageBoxEx.Show("Error Code: 0x002");
}
finally
{
workbookData.Close();
}
//宏记录操作,可将里面的代码复制到程序中使用
文章来源地址https://www.toymoban.com/news/detail-531972.html文章来源:https://www.toymoban.com/news/detail-531972.html
到了这里,关于C#调用Microsoft.Office.Interop.Excel时的常见操作功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!