public string ExportToExcel(System.Web.UI.Page objPage, DataView dbDtViewWrk, string[] cols)
{
if ((dbDtViewWrk.Count == 0) || (dbDtViewWrk == null))
{
return "-2";
}
if ((cols.Length == 0) || (cols == null))
{
return "-2";
}
string strAbsolutePath = clsCommon.GetUploadFilePath(objPage, clsCommon.genmUploadFileKind.Templete, "");
string strRelativePath = clsCommon.GetUploadFileUrl(objPage, clsCommon.genmUploadFileKind.Templete, "");
Object Nothing = System.Reflection.Missing.Value;
//取得Excel文件保存路径
string strFileNm = DateTime.Now.ToString("yyyyMMddHHmmssffff");
string strFileName = strFileNm + ".XLS";
object filename = strAbsolutePath + strFileName;
Excel.Application myExcel = new Excel.ApplicationClass();
try
{
//创建excel文件
myExcel.Application.Workbooks.Add(Nothing);
for (int j = 1; j <= cols.Length; j++)
{
myExcel.Cells[1, j] = cols[j - 1];
}
for (int i = 1; i <= dbDtViewWrk.Count; i++)
{
for (int j = 1; j <= cols.Length; j++)
{
myExcel.Cells[i + 1, j] = dbDtViewWrk[i - 1][j - 1];
}
}
//保存excel文件到指定的目录下
myExcel.ActiveWorkbook.SaveAs(filename, Nothing, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
//关闭Excel Work Book对象
myExcel.ActiveWorkbook.Close(Nothing, Nothing, Nothing);
//关闭Excel组件对象
myExcel.Quit();
}
catch (Exception e)
{
return "-1";
}
finally
{
//释放相关资源
myExcel = null;
GC.Collect();
}
return strRelativePath + strFileName;
}
public string ExportToExcel(System.Web.UI.Page objPage, DataTable dbDtViewWrk)
{
if (dbDtViewWrk == null)
{
return "-2";
}
string strAbsolutePath = clsCommon.GetUploadFilePath(objPage, clsCommon.genmUploadFileKind.Templete, "");
string strRelativePath = clsCommon.GetUploadFileUrl(objPage, clsCommon.genmUploadFileKind.Templete, "");
int col=dbDtViewWrk.Columns.Count;
int row=dbDtViewWrk.Rows.Count;
Object Nothing = System.Reflection.Missing.Value;
//取得Excel文件保存路径
string strFileNm = DateTime.Now.ToString("yyyyMMddHHmmssffff");
string strFileName = strFileNm + ".XLS";
object filename = strAbsolutePath + strFileName;
Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
//创建excel文件
myExcel.Application.Workbooks.Add(Nothing);
for (int j = 1; j <= col; j++)
{
myExcel.Cells[1, j] = dbDtViewWrk.Columns[j].ColumnName;
}
for (int i = 0; i < col; i++)
{
for (int j = 1; j <= row; j++)
{
myExcel.Cells[i + 1, j] = dbDtViewWrk.Rows[i][j - 1].ToString();
}
}
//保存excel文件到指定的目录下
myExcel.ActiveWorkbook.SaveAs(filename, Nothing, Nothing, Nothing, Nothing, Nothing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
//关闭Excel Work Book对象
myExcel.ActiveWorkbook.Close(Nothing, Nothing, Nothing);
//关闭Excel组件对象
myExcel.Quit();
}
catch (Exception e)
{
return "-1";
}
finally
{
//释放相关资源
myExcel = null;
GC.Collect();
}
return strRelativePath + strFileName;
}