日期:2014-05-19  浏览次数:20916 次

???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);