分享

C#导出EXCEL 并解决EXCEL进程问题!

 COPY&PASTE 2009-10-05
C#导出EXCEL 并解决EXCEL进程问题!
2008年08月04日 星期一 14:01
 

大家看下我的完整代码吧:
public void daochu_all(DataSet exl_target, DataSet exl_workRTC, DataSet exl_workType, DataSet exl_rateAdd, DataSet exl_ratePhase, DataSet exl_bugRemove, DataSet exl_reviewSpeed, string path)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlBook = null;
string fullpath = path.Substring(0, path.Length - 4) + "fileupload ";
string templatepath = fullpath + "\\BaselineTemplate ";
string productpath = fullpath + "\\BaselineProduct ";
string userpath = templatepath + "\\excel.xls ";

DirectoryInfo dtemplate = new DirectoryInfo(templatepath);
DirectoryInfo dproduct = new DirectoryInfo(productpath);

if (dtemplate.Exists)
{
}
else
{
Directory.CreateDirectory(templatepath);
}

if (dproduct.Exists)
{
}
else
{
Directory.CreateDirectory(productpath);
}

if (File.Exists(userpath))
{
try
{
xlBook = xlApp.Workbooks.Add(userpath);
//xlSheet = (Excel.Worksheet)xlApp.Worksheets.get_Item( "项目性能查询 (性能基线表) ");

System.Data.DataTable Table_target = exl_target.Tables[0];
System.Data.DataTable Table_workRTC = exl_workRTC.Tables[0];
System.Data.DataTable Table_workType = exl_workType.Tables[0];
System.Data.DataTable Table_rateAdd = exl_rateAdd.Tables[0];
System.Data.DataTable Table_ratePhase = exl_ratePhase.Tables[0];
System.Data.DataTable Table_bugRemove = exl_bugRemove.Tables[0];
System.Data.DataTable Table_reviewSpeed = exl_reviewSpeed.Tables[0];
double a = Convert.ToDouble(Table_target.Rows[0][2]);
double a1 = Convert.ToDouble(Table_target.Rows[0][3]);
double a2 = Convert.ToDouble(Table_target.Rows[0][4]);

double a3 = Convert.ToDouble(Table_target.Rows[1][2]);
double a4 = Convert.ToDouble(Table_target.Rows[1][3]);
double a5 = Convert.ToDouble(Table_target.Rows[1][4]);

//--------------------整体性能-------------------

int Tablerow = 5;


for (int i = 0; i < Table_target.Rows.Count; i++)//取记录值
{
string tmpName = Table_target.Rows[i][0].ToString();

for (int j = 0; j < (Table_target.Columns.Count - 2); j++)
{

if (tmpName == "1 " || tmpName == "2 " || tmpName == "5 ")
{
xlApp.Cells[Tablerow, j + 2] = Convert.ToDouble((Table_target.Rows[i][j + 2].ToString())) / 100;
}
else
{
xlApp.Cells[Tablerow, j + 2] = Table_target.Rows[i][j + 2].ToString();
}

}
Tablerow++;
}

//--------------------工作量比重-相对于编码-------------------

int Table2row = 16;

for (int i = 0; i < Table_workRTC.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_workRTC.Columns.Count - 2); j++)
{

xlApp.Cells[Table2row, j + 2] = Table_workRTC.Rows[i][j + 2].ToString();

}
Table2row++;
}

//--------------------各类工作比例-------------------

int Table3row = 32;

for (int i = 0; i < Table_workType.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_workType.Columns.Count - 2); j++)
{

xlApp.Cells[Table3row, j + 2] = Convert.ToDouble((Table_workType.Rows[i][j + 2].ToString())) / 100;

}
Table3row++;
}

//--------------------缺陷排除率-累计-------------------

int Table4row = 56;

for (int i = 0; i < Table_rateAdd.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_rateAdd.Columns.Count - 2); j++)
{

xlApp.Cells[Table4row, j + 2] = Convert.ToDouble((Table_rateAdd.Rows[i][j + 2].ToString())) / 100;

}
Table4row++;
}

//--------------------缺陷排除率-当前阶段-------------------

int Table5row = 71;

for (int i = 0; i < Table_ratePhase.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_ratePhase.Columns.Count - 2); j++)
{

xlApp.Cells[Table5row, j + 2] = Convert.ToDouble((Table_ratePhase.Rows[i][j + 2].ToString())) / 100;

}
Table5row++;
}

//--------------------缺陷排除密度-------------------

int Table6row = 84;

for (int i = 0; i < Table_bugRemove.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_bugRemove.Columns.Count - 2); j++)
{

xlApp.Cells[Table6row, j + 2] = Table_bugRemove.Rows[i][j + 2].ToString();

}
Table6row++;
}

//--------------------评审速度-------------------

int Table7row = 99;

for (int i = 0; i < Table_reviewSpeed.Rows.Count; i++)//取记录值
{

for (int j = 0; j < (Table_reviewSpeed.Columns.Count - 2); j++)
{

xlApp.Cells[Table7row, j + 2] = Table_reviewSpeed.Rows[i][j + 2].ToString();

}
Table7row++;
}

xlApp.Application.DisplayAlerts = false;
xlBook.SaveAs(productpath + "\\BaselineProduct.xls ", xlApp.ActiveWorkbook.FileFormat, " ", " ", xlApp.ActiveWorkbook.ReadOnlyRecommended, xlApp.ActiveWorkbook.CreateBackup, XlSaveAsAccessMode.xlNoChange, xlApp.ActiveWorkbook.ConflictResolution, false, " ", " ", " ");
}
catch
{
throw new Exception( "生成性能基线所需模板或数据库中数据有误 ");
}
finally
{
Process[] processes = Process.GetProcesses;
Process process;
foreach (process in processes)
{

}

if (xlBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
xlBook = null;
}
if (xlApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp.Quit();
xlApp = null;
}
GC.Collect();
}
}
else
{
throw new Exception( "服务器BaselineTemplate中未发现模板文件 ");
}
}

 

我也碰到过,解决的方法和JoneG(琼琼) 说的一样,只是我是把所有excel操作放到一个方法里(包括xlApp.Quit();等),然后在方法外面再GC.Collect();
如 public voic excel操作处理(string path)
{
........
}

调用处
excel操作处理(strpath;
GC.Collect();
这样应该就可以了

最好不要杀进程

public void aaa()
{
bbb();
System.GC.Collect(); //在这里调用垃圾收集
}

public void bbb()
{
操作excel();
该怎么处理还是怎么处理
}

就OK了

public void DestoryExcel()
{
oBook.Close( false, null, null );
oExcel.Workbooks.Close();
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject( oRange );
System.Runtime.InteropServices.Marshal.ReleaseComObject( oWorkSheet );
System.Runtime.InteropServices.Marshal.ReleaseComObject( oSheet );
System.Runtime.InteropServices.Marshal.ReleaseComObject( oBook );
System.Runtime.InteropServices.Marshal.ReleaseComObject( oExcel );
oRange = null;
oWorkSheet = null;
oSheet = null;
oBook = null;
oMissing = null;
oExcel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}

如果是WinForm程式的话

Excel.ApplicationClass exc = new Excel.ApplicationClass ();

if ( exc == null )
{
MessageBox.Show ( "ERROR: EXCEL couldn 't be started ");
}

Excel.Workbooks exBooks=null;
Excel._Workbook exBook=null;
Excel._Worksheet exSheet=null;
object mo=System.Reflection.Missing.Value;

try
{
exc=new Excel.ApplicationClass();
exBooks=exc.Workbooks;
exBook=exBooks.Open(ExcelFile.Text,mo,mo,mo,mo,mo,mo,mo,mo,mo,mo,mo,mo);
exSheet = (Excel._Worksheet)exBook.Worksheets[ "Equipments "];//Sheet1为你工作表的名称,也可以是数字,那就是你工作表的序号
....
}
catch( System.Exception exp)
{
MessageBox.Show (exp.Message );
}
finally
{
//exBook.Save();

exBook.Close(true,mo,mo);
exBooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(exSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);

System.Runtime.InteropServices.Marshal.ReleaseComObject(exBooks);
exBooks=null;
exBook = null;
exSheet = null;
exc.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(exc);
exc = null;
GC.Collect();

}

就可以直接结束掉了.

如果是Web程式

System.DateTime begintime ; //启动之前的时间
System.DateTime afterTime; //启动之后的时间

在Excel对象初始化前记录启动之前的时间

//初始化
===========================================================================
begintime = System.DateTime .Now ;

Excel.ApplicationClass exc = null;

....
==========================================================================

操作完成后
=============================================================================

afterTime = System.DateTime .Now ; //启动之后的时间
//释放资源
KillExcelProcess(begintime,afterTime); //强行结束Excel进程
=============================================================================
KillExcelProcess()函数

public void KillExcelProcess(System.DateTime beginTime, System.DateTime afterTime)
{
try
{
System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName( "Excel ");

foreach(System.Diagnostics.Process process in excelProcess)
{
if (process != null)
{
if ( process.StartTime > beginTime && process.StartTime < afterTime )
{
process.Kill();
}
}
}
}
catch(System.Exception exp)
{
Response.Write ( " <script> alert( ' "+exp.Message + " '); </script> ");
}
}

 


// <summary>
/// 退出系统杀进程
/// </summary>
private void KillProcess()
{
System.Diagnostics.Process CurrentProcess = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] AllProcess = System.Diagnostics.Process.GetProcesses();

foreach (System.Diagnostics.Process p in AllProcess)
{
if (p.Id == CurrentProcess.Id)
p.Kill();
}

}

 


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约