#region Exel文件导出函数
protected object missing = Missing.Value;
public string DataSetToExcel(DataTable dt, string tpFile, string filePath, string saveFileName, int templateID, string outFileType)
{
System.Data.DataTable visibleCol = SysModelTypeLogic.GetVisibleColByTypeAndUserID(templateID, UserState.CurrentUser.UserID).Tables[0];
#region 获取Excel模板对象
Excel.Application app = new Excel.ApplicationClass();
app.Visible = false;
//打开模板文件,得到WorkBook对象
Excel.Workbook workBook = app.Workbooks.Open(tpFile, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing);
//得到WorkSheet对象
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
#endregion
#region 将源DataTable数据写入Excel
#region 导入标题
Excel.Range titleRange = workSheet.get_Range(workSheet.Cells[1, 1], workSheet.Cells[2, visibleCol.Rows.Count]);
titleRange.Merge(true);//合并列
titleRange.MergeCells = true;//合并单元格
titleRange.Value2 = saveFileName;
titleRange.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//水平居中
titleRange.Font.Size=14;//设置字体大小
#endregion
#region 导入列名
Excel.Range range;
for (int i = 0; i < visibleCol.Rows.Count; i++)
{
workSheet.Cells[3, i + 1] = visibleCol.Rows[i]["HeaderText"].ToString();
range = (Excel.Range)workSheet.Cells[3, i + 1];
range.Cells.Borders.LineStyle = 1;
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Silver);
if (visibleCol.Rows[i]["HeaderStyle-Width"] != DBNull.Value && !string.IsNullOrEmpty(visibleCol.Rows[i]["HeaderStyle-Width"].ToString()))
{
range.ColumnWidth = Convert.ToDouble(visibleCol.Rows[i]["HeaderStyle-Width"]) / 6;
}
range.Font.Bold = true;
range.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
}
#endregion
#region 导入数据
Excel.Range borderRange;
string columnName = string.Empty;
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < visibleCol.Rows.Count; j++)
{
if (visibleCol.Rows[j]["DataField"] != null)
{
columnName = visibleCol.Rows[j]["DataField"].ToString();
if (dt.Columns[columnName].ToString() == visibleCol.Rows[j]["DataField"].ToString())
{
workSheet.Cells[i + 4, j + 1] = dt.Rows[i][columnName].ToString()+ "\r";//转换为字符串
borderRange = (Excel.Range)workSheet.Cells[i + 4, j + 1];
borderRange.Cells.Borders.LineStyle = 1;
#region 设置对齐方式
if (visibleCol.Rows[j]["ItemStyle-HorizontalAlign"] != DBNull.Value && !string.IsNullOrEmpty(visibleCol.Rows[j]["ItemStyle-HorizontalAlign"].ToString()))
{
string horizontalAlign = visibleCol.Rows[j]["ItemStyle-HorizontalAlign"].ToString().ToLower();
switch (horizontalAlign)
{
case "right":
borderRange.HorizontalAlignment = 4;
break;
case "center":
borderRange.HorizontalAlignment = 3;
break;
case "left":
borderRange.HorizontalAlignment = 2;
break;
default:
break;
}
}
#endregion
#region 自动求和(添加合计行)
if (visibleCol.Rows[j]["AllowSum"] != DBNull.Value && !string.IsNullOrEmpty(visibleCol.Rows[j]["AllowSum"].ToString()))
{
string allowSum = visibleCol.Rows[j]["AllowSum"].ToString();
Excel.Range totalRange;
if (allowSum == "1")//需要合计
{
workSheet.Cells[dt.Rows.Count + 4, j + 1] = "=sum(R[-" + (i + 1).ToString() + "]C:R[-1]C)";
}
else
{
workSheet.Cells[dt.Rows.Count + 4, j + 1] = "";
}
totalRange = (Excel.Range)workSheet.Cells[dt.Rows.Count + 4, j + 1];
totalRange.Cells.Borders.LineStyle = 1;
}
#endregion
#region 设置格式
if (visibleCol.Rows[j]["DataType"] != DBNull.Value && !string.IsNullOrEmpty(visibleCol.Rows[j]["DataType"].ToString()))
{
string dataType = visibleCol.Rows[j]["DataType"].ToString().ToLower();
if (dataType == "decimal")//设置金额,格式保留两位小数
{
borderRange.NumberFormatLocal = "0.00";
}
else if (dataType == "datetime")//设置日期格式
{
borderRange.NumberFormatLocal = "yyyy-mm-dd";
}
else if(dataType=="string")
{
workSheet.Cells[i + 2, j + 1] = dt.Rows[i][columnName].ToString()+"\r";
//borderRange.NumberFormatLocal = "@ ";//转换为字符串
//borderRange.NumberFormat = Excel.XlParameterDataType.xlParamTypeUnknown;
}
}
#endregion
}
}
}
}
#endregion
#endregion
#region 输出Excel文件并退出
try
{
//app.DisplayAlerts = false;
saveFileName = saveFileName + "(" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + UserState.CurrentUser.EmployeeCName + ").xls";
string fileName = filePath + saveFileName;
workBook.SaveAs(fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
//app.AlertBeforeOverwriting = false;//保存时不提示文件已经存在,是不覆盖。
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
Marshal.ReleaseComObject(workSheet);
Marshal.ReleaseComObject(workBook);
Marshal.ReleaseComObject(app);
workSheet = null;
workBook = null;
app = null;
GC.Collect();
}
catch (Exception e)
{
throw e;
}
finally
{
//Process[] myProcesses;
//DateTime startTime;
//myProcesses = Process.GetProcessesByName("Excel");
////得不到Excel进程ID,暂时只能判断进程启动时间
//foreach (Process myProcess in myProcesses)
//{
// startTime = myProcess.StartTime;
// myProcess.Kill();
//}
}
#endregion
#region 打开Excel
return outFileType.Replace("~/", "相对路径") + saveFileName;
//Response.Redirect(outFileType.Replace("~/", "相对路径") + saveFileName, true);
#endregion
}
#endregion