随风而行

^o^ 格言:相信没有做不到的事情,只有想不到的事情.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

将数据导入指定的Excel模版中

Posted on 2009-02-23 11:07  随风而行  阅读(331)  评论(0编辑  收藏  举报

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OracleClient;
using Microsoft.Office.Interop.Excel;
using System.Collections.Generic;
using System.Text;
using System.IO;

private void Excel_data()

{

        System.DateTime MINI = System.DateTime.Now;
        string times = MINI.ToString("yyyy-MM-dd HH:mm:ss");       
        Session["times"] = times.ToString();
        string dayin_times = MINI.ToString("yyyy-MM-dd HH:mm");       

        string path = Server.MapPath("/web/Product/Web/Sample/faliaobiao.xls");
        string excelPath = Server.MapPath("/web/" + Guid.NewGuid() + ".xls");
        
        ExcelHander OpenFile = new ExcelHander();
        OpenFile.OpenExcelFile(path);
        Worksheet datasheet = null;
        Sheets sheets = OpenFile.CurrentWorkBooks[1].Worksheets;
        foreach (Worksheet sheet in sheets)
        {
            if (sheet.Name == "Sheet1")
            {
                datasheet = sheet;
                break;
            }
        }
        datasheet.Cells[1, 14] = dayin_times.ToString().Trim();
        datasheet.Cells[3, 2] = lblmateriel_id.Text.Trim().ToString() +"   "+lblmateriel_name.Text.Trim().ToString();
        datasheet.Cells[3, 12] = lblstart_date.Text.Trim().ToString();
        datasheet.Cells[3, 7] = lblworkorder.Text.Trim().ToString();
        datasheet.Cells[3, 10] = lblnum.Text.Trim().ToString();
            int colIndex = 1, rowIndex = 5;
            foreach (DataRow row in Table1.Rows)
            {
                rowIndex++; colIndex = 0;
                foreach (DataColumn col in Table1.Columns)
                {
                    colIndex++;
                    if (colIndex == 0)
                    {
                        datasheet.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
                    }
                    else
                    {
                        datasheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                    }
                }
            }
        OpenFile.SaveAs(excelPath);
        sheets = null;
        OpenFile.ReleaseExcel();
        OpenFile.KillAllExcelApp();
           
        Response.End();

}