⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 program.cs

📁 [Visual C# 2005程序设计基础教程] 全部的源码!非常经典
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using excel = Microsoft.Office.Interop.Excel;


namespace VSTOExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            object missing = Missing.Value;
            //实例化一个Application对象
            excel.Application eApp = new Microsoft.Office.Interop.Excel.Application();
            //打开目标文件
            excel.Workbook wb = eApp.Workbooks.Open(@"C:\\sample.xls", missing, missing, missing,
            missing, missing, missing, missing, missing,
            missing, missing, missing, missing, missing, missing);
            eApp.Visible = true;
            //删除除第一个Sheet外的其他工作表
            foreach (excel.Worksheet wsheet in eApp.Workbooks[1].Worksheets)
            {
                if (wsheet.Name != "Sheet1")
                {
                    wsheet.Delete();
                }
            }
            //新建一个工作表,命名为SampSheet,位置在Sheet1后面
            object after = eApp.Workbooks[1].Worksheets.Count;
            excel.Worksheet ws = (excel.Worksheet)eApp.Workbooks[1].Worksheets.Add(missing, eApp.
            Workbooks[1].Worksheets[1], missing, missing);
            ws.Name = "SampSheet";
            //从sheet1中读取数据到SampSheet中
            string text;
            for (int i = 2; i <= 29; i++)
            {
                //写入处理第一列
                excel.Range rg3 = ((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).
                get_Range(((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).Cells[i, 2],
                ((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).Cells[i, 2]);
                text = rg3.Text.ToString();
                rg3 = (excel.Range)ws.get_Range(ws.Cells[i, 1], ws.Cells[i, 1]);
                rg3.Value2 = text;
                //写入第二列
                rg3 = ((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).
                get_Range(((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).Cells[i, 6],
                ((excel.Worksheet)eApp.Workbooks[1].Worksheets[1]).Cells[i, 6]);
                text = rg3.Text.ToString();
                rg3 = (excel.Range)ws.get_Range(ws.Cells[i, 2], ws.Cells[i, 2]);
                rg3.Value2 = text;
                //设置Cell格式
                if (Convert.ToDouble(text) < 60)
                    rg3.Font.ColorIndex = 3;
            }

            //保存对文档所作修改
            foreach (excel.Workbook w in eApp.Workbooks)
            {
                w.Save();
            }

        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -