MyException - 我的异常网
当前位置:我的异常网» C# » ?excel.dll 操作excel得通用类,该如何解决

?excel.dll 操作excel得通用类,该如何解决

www.MyException.Cn  网友分享于:2013-12-31  浏览:20次
???excel.dll 操作excel得通用类
谁有比较好的用excel.dll操作excel,   比如导出,读取excel得   通用类?

------解决方案--------------------
.NET不是提供OFFICE一组COM组件,在项目中引入OFFICE组件就可以了
需要添加COM: Microsoft Excel Object Library.

一些例子,可以参考一下
/// <summary>
/// 将DataSet里所有数据导入Excel.
/// 需要添加COM: Microsoft Excel Object Library.
/// using Excel;
/// </summary>
/// <param name= "filePath "> </param>
/// <param name= "ds "> </param>
public void ExportToExcel(string savePath,string templatePath, DataSet ds)
{
string strResult = LoadExcelModel(templatePath);
if (strResult == " ")
{
//excel.Visible = true;

try
{
WriteExcel(ds,savePath);

}
catch
{
//MessageBox.Show(ex.ToString(), "错误 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
//MessageBox.Show(strResult, "错误 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

#region 载入模板文件
private string LoadExcelModel(string filePath)
{
//
try
{
//for excel2000
// excel.Workbooks.Open(filePath,oMissing,oMissing,
// oMissing, oMissing, oMissing, oMissing,
// oMissing, oMissing, oMissing, oMissing,
// oMissing, oMissing);

//for excel2003

excel.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
}
catch (Exception ex)
{
return ex.Message;
}

return " ";
}
#endregion

#region 生成excel文件内容
private void WriteExcel(DataSet ds,string savePath)
{
Excel.Workbook xlWorkbook = (Excel.Workbook)(excel.ActiveWorkbook);
Excel.Worksheet xlWorksheet = (Excel.Worksheet)(xlWorkbook.Sheets[sheetName]);
//xlWorksheet.Activate();
xlWorksheet.Unprotect(null);
((Excel.Worksheet)(xlWorkbook.Sheets[1])).Activate();

xlWorksheet.Name = sheetName;

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
{
int rowIndex = i + 3;
int colIndex = k + 1;
xlWorksheet.Cells[rowIndex, colIndex] = ds.Tables[0].Rows[i][k].ToString();
}
}

excel.Run( "Run ", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

//锁定基础数据表
//for excel2000
// xlWorksheet.Protect(oMissing,true,true,true,oMissing);
//for excel2003
xlWorksheet.Protect(oMissing, true, true, true, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有