///DataObject[] 可以把它試做爲DataTable
private void ExportExcel(DataObject[] objs)
{
//讀取Excel路徑
string excelSource = Server.MapPath("SIP016Export.xls");
string FileName = "SIP016Export.xls";
string tempFolder = "../../../tempFolder/";
string tempFilePath = Server.MapPath(tempFolder + FileName);
File.Copy(excelSource, tempFilePath, true);
object missing = System.Type.Missing;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = app.Workbooks._Open(tempFilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
app.Visible = false;
for (int i = 0; i < objs.Length; i++)
{
worksheet.Cells[i + 2, 1] = objs[i].getData("SUNITATRR_CV");
worksheet.Cells[i + 2, 2] = objs[i].getData("SORG_CV");
worksheet.Cells[i + 2, 3] = objs[i].getData("SSUBJECT_CV");
worksheet.Cells[i + 2, 4] = objs[i].getData("SMSUBJECT_CV");
}
worksheet.Columns.EntireColumn.AutoFit();//列寬自適應
workbook.Save();
app.Quit();
string path = GetRootURI() + "/tempFolder/SIP016Export.xls?date=" + DateTime.Now.ToString();
Response.Write("window.open('" + path + "','download','height=50,width=50,top=0,left=0');");
}
/// <summary>
/// 獲取平臺web物理路徑
/// </summary>
/// <returns></returns>
public string GetRootURI()
{
string AppPath = "";
HttpContext HttpCurrent = HttpContext.Current;
HttpRequest Req;
if (HttpCurrent != null)
{
Req = HttpCurrent.Request;
string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
{
AppPath = UrlAuthority;
}
else
{
AppPath = UrlAuthority + Req.ApplicationPath;
}
}
return AppPath;
}