【C#常用操作】

excel相关操作

using Excel = Microsoft.Office.Interop.Excel;

public Excel.Application app;
public Excel.Workbooks wbs;
public Excel.Workbook wb;
public Excel.Worksheets wss;
public Excel.Worksheet ws;

/// 
/// 取得打开excel句柄
/// 
/// 打开文件路径
public void excel_Open(string pathfilename)
{
    app = new Microsoft.Office.Interop.Excel.Application();
    wb = app.Workbooks.Open(pathfilename,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing,
        Type.Missing);
}
/// 
/// 释放句柄,并关闭excel进程
/// 
public void excel_ReleaseResource()
{
    app.DisplayAlerts = false;     //保存Excel的时候,不弹出是否保存的窗口直接进行保存 

    app.AlertBeforeOverwriting = false;
    wb.Save();
    app.Quit();
    wb = null;
    wbs = null;
    
    GC.Collect();//垃圾回收

    Kill(app);
    app = null;
}

/// 
/// 引用dll接口
/// 
/// 句柄
/// 进程ID
/// 
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd,out int ID);
/// 
/// 关闭进程
/// 
/// excel应用变量
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{   
    IntPtr t=new IntPtr(excel.Hwnd);//得到这个句柄,具体作用是得到这块内存入口 

    int k= 0;   
    GetWindowThreadProcessId(t,out k);   //得到本进程唯一标志k
    System.Diagnostics.Process p=System.Diagnostics.Process.GetProcessById(k);   //得到对进程k的引用
    p.Kill();     //关闭进程k
}


//向excel中插入图片
public void excel_setImage()
{
    //读取图片
    System.Drawing.Image myimage = Image.FromFile(PicPath+strPictureName+".png");
    System.Drawing.Size size = new Size(myimage.Width, myimage.Height);
    string imagewidth = size.Width.ToString();//图片的宽度
    string imagehight = size.Height.ToString();//图片的高度

    excel_Open(strExcelPath);
    ws = (Excel.Worksheet)wb.Sheets[2];

    ((Excel.Range)ws.Cells[1][1]).Select();
    ((Excel.Range)ws.Cells[1][1]).Activate();
    ((Excel.Range)ws.Cells[1][1]).RowHeight = 100;
    float PicLeft, PicTop;
    //为了图片能够适应单元格的宽高进行的转换
    PicLeft = Convert.ToSingle(((Excel.Range)ws.Cells[insertColumn][iRowNum + 8]).Left);
    PicTop = Convert.ToSingle(((Excel.Range)ws.Cells[insertColumn][iRowNum + 8]).Top);
    ws.Shapes.AddPicture(strImagePath, Office.Core.MsoTriState.msoFalse, Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, iWidth, iHight);

    app.DisplayAlerts = false;     //保存Excel的时候,不弹出是否保存的窗口直接进行保存 
    app.AlertBeforeOverwriting = false;
    wb.Save();
    app.Quit();
    wb = null;
    wbs = null;

    GC.Collect();//垃圾回收

    Kill(app);
    app = null;

    using (FileStream fs = File.Create(path))
    {
        AddText(fs, "SetImage:" + strImagePath);
    }
}

sheet操作

ws = (Excel.Worksheet)wb.Worksheets["Sheet1"];

ws = (Excel.Worksheet)wb.Sheets[1];

range/cell操作

Excel.Range range = ws.Range[ws.Cells[1, 1], ws.Cells[10, 10]];

int rowsint = ws.Range["C65535"].End[Excel.XlDirection.xlUp].Row;//取得有效数据的行数
int columnsint = ws.Range["IV4"].End[Excel.XlDirection.xlToLeft].Column;//取得有效数据的列数
(Excel.Range)ws.Cells[1, 1]).Text//取得或赋值单元格内容

//单元格底色
((Excel.Range)ws.Cells[1, 1]).Interior.ColorIndex = 3;

操作已打开的excel

Workbooks xlBooks;
Workbook xlBook;
Worksheet xlSheet;

public void excel_Test()
{
    // 声明一个对象
    Excel._Application objExcel;
    objExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    objExcel.Visible = true;
    xlBooks = objExcel.Workbooks;

    var numBooks = xlBooks.Count;
    //大于0说明有多个excel被打开
    if (numBooks > 0)
    {
        //第一个一般是最后被激活的那个excel
        xlBook = xlBooks[1];
        // 这里要注意,一定要使用被激活的sheet,否则后续这个sheet句柄无法进行操作
        xlSheet = (Worksheet)xlBook.ActiveSheet;
        //range不能直接用
        //xlSheet.Range[1, 1].Select(); 错误
        xlSheet.Cells[1, 1].Select();
    }
}

其他常用处理

//延时处理
public static void Delay(int milliSecond)
{
    int start = Environment.TickCount;
    while (Math.Abs(Environment.TickCount - start) < milliSecond)//毫秒
    {
        System.Windows.Forms.Application.DoEvents();//可执行某无聊的操作
    }
}

你可能感兴趣的:(c#,开发语言)