更多关于C# 操作EXCEL
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections;
using System.Windows.Forms;
namespace Newcapec.CeditCard.BLL
{
public class ExcelOpertor
{
//导入进度百分比
private float percent = 0;
/// <summary>
/// 导入进度百分比
/// </summary>
public float Percent
{
get
{
return percent;
}
set
{
percent = value;
}
}
/// <summary>
/// 将dataset导出至excel中,可选择只导出dataset的头
/// </summary>
/// <param name="ds"></param>
/// <param name="SaveFile"></param>
/// <param name="ifHead"></param>
public void DataSetToExcel(DataSet ds, string SaveFile, bool ifHead)
{
Excel.Application excel;
Excel._Workbook xbk;
Excel._Worksheet xst;
object misValue = System.Reflection.Missing.Value;
excel = new Excel.ApplicationClass();
xbk = excel.Workbooks.Add(misValue);
percent += 0.15f;
//如果是导出数据后,打开excel
//excel.Workbooks.Open(filename,0,readyonly,5,"","",true,Excel.XlPlatform.xlWindows,
xst = (Excel._Worksheet)xbk.ActiveSheet;
int rowIndex = 1;
int colIndex = 0;
//取得标题
foreach (DataColumn col in ds.Tables[0].Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
percent += 0.15f;
if (!ifHead)
{//如果不是只出头,则将数据填进去
//取得表格中的数据
foreach (DataRow row in ds.Tables[0].Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in ds.Tables[0].Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
//设置表格内容居中对齐
xst.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
}
}
}
percent += 0.15f;
excel.Visible = false;
xbk.SaveAs(SaveFile, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
ds = null;
xbk.Close(true, misValue, misValue);
excel.Quit();
PublicMethod.Kill(excel);//调用kill当前excel进程
releaseObject(xst);
releaseObject(xbk);
releaseObject(excel);
percent += 0.15f;
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
}
public class PublicMethod
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
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
}
}
}