日期:2014-05-18  浏览次数:20941 次

关于EXCEL导出的问题
if(listView1.Items.Count==0)
{
return;

string SavaFileName="";
bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt="xls";
  saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName="sheet1";
saveDialog.ShowDialog();
SavaFileName=saveDialog.FileName;
if(SavaFileName.IndexOf(":")<0)
{
//用户点了取消.
return;
}
Excel.Application xlApp=new Excel.ApplicationClass();
if(xlApp==null)
{
MessageBox.Show("无法创建EXCEL对象,可能您的机器未安装EXCEL","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1


long totalCount=this.listView1.Items.Count;
long rowRead=0;
float percent=0;

//写入表头
for(int i=0;i<listView1.Columns.Count;i++)
{
worksheet.Cells[1,i+1]=this.listView1.Columns[i].Text.ToString();
}

//设置表头样式
Excel.Range productTitle=worksheet.get_Range(worksheet.Cells[1,1],worksheet.Cells[1,this.listView1.Columns.Count]);
productTitle.Font.ColorIndex=5;
productTitle.Font.Bold=true;
productTitle.HorizontalAlignment=Excel.XlHAlign.xlHAlignCenter;
productTitle.VerticalAlignment=Excel.XlVAlign.xlVAlignBottom;

//写入数值
this.label2.Visible=true;
  worksheet.Cells.NumberFormat = "@ ";
   
for(int j=0;j<this.listView1.Items.Count;j++)
{
for(int k=0;k<listView1.Columns.Count;k++)
{
   
worksheet.Cells[j+2,k+1]=this.listView1.Items[j].SubItems[k].Text;
   
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
this.label2.Text="正在导出数据['"+percent.ToString("0.00")+"'%]";
}
  worksheet.Columns.AutoFit();

if(SavaFileName!="")
{
try
{
workbook.Saved=true;
workbook.SaveCopyAs(SavaFileName);
fileSaved=true;
}
catch(Exception ex)
{
MessageBox.Show("导出文件出错,文件可能正被打开!\n"+ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
else
{
fileSaved=false;
}
xlApp.Quit();
xlApp=null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
worksheet=null;
workbook=null;

if(fileSaved&&File.Exists(SavaFileName))
{
MessageBox.Show("导出成功","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
本机使用没问题
测试机出现错误


------解决方案--------------------
缺少DLL吧,看下bin目录下有没有 Microsoft.Office.Interop.Excel.dll
------解决方案--------------------
探讨

未能加载文件或程序集“interop excel , version=1.5.0.0,culture=neutral , publickeytoken=null"或它的某一个依赖项。系统找不到指定的文件