save tables to excel sheets class and down load class
            做了一个对页面的四张表单保存到Excel中的四个Sheet中,并提供下载 , 本来想在客户端完成操作, 实在没想出来好的解决办法,如果谁有请告诉我, 我实现了先把形成的Excel生成并保存到服务器端,当然服务器端要进行一些配置,允许客户端对服务器端保存Excel。服务器用的是win2003,打开管理中的组件服务,找到DCOM配置 --> Microsoft Excel 应用程序 -- > 属性 ,对访问权限进行自定义配置,添加EveryOne用户,给予全部权限。
下面给出相应的页面部分代码,和download类和SaveExcel类。
 SaveExcel command and close view command;
SaveExcel command and close view command;
 using System;
using System;
 using System.Data;
using System.Data;
 using System.Configuration;
using System.Configuration;
 using System.Web;
using System.Web;
 using System.Web.Security;
using System.Web.Security;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls;
 using System.IO;
using System.IO;
 using System.Threading;
using System.Threading;

 /// <summary>
/// <summary>
 /// DownLoad 的摘要说明
/// DownLoad 的摘要说明
 /// </summary>
/// </summary>
 public class DownLoad
public class DownLoad
 {
{
 private DownLoad()
    private DownLoad()
 {}
    {}

 /// <summary>
    /// <summary>
 /// 下载函数
    /// 下载函数
 /// </summary>
    /// </summary>
 /// <param name="H_Request">能够读取客户端在WEB请求发送期间发送的HTTP值</param>
    /// <param name="H_Request">能够读取客户端在WEB请求发送期间发送的HTTP值</param>
 /// <param name="H_Response">封装asp.net操作的HTTP响应信息</param>
    /// <param name="H_Response">封装asp.net操作的HTTP响应信息</param>
 /// <param name="FileName">文件名:aa.txt</param>
    /// <param name="FileName">文件名:aa.txt</param>
 /// <param name="FullPath">绝对路径:Server.MapPath("Department"+Str_FullPath)//Str_FullPath=\aa.txt</param>
    /// <param name="FullPath">绝对路径:Server.MapPath("Department"+Str_FullPath)//Str_FullPath=\aa.txt</param>
 /// <param name="Speed">当前线程被阻塞的毫秒数</param>
    /// <param name="Speed">当前线程被阻塞的毫秒数</param>
 /// <returns></returns>
    /// <returns></returns>
 public static bool ResponseFile(HttpRequest H_Request, HttpResponse H_Response, string FileName, string FullPath, long Speed)
    public static bool ResponseFile(HttpRequest H_Request, HttpResponse H_Response, string FileName, string FullPath, long Speed)
 {
    {
 try
        try
 {
        {
 System.IO.FileStream File = new FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
            System.IO.FileStream File = new FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
 System.IO.BinaryReader BR = new BinaryReader(File);
            System.IO.BinaryReader BR = new BinaryReader(File);
 try
            try
 {
            {
 H_Response.AddHeader("Accept-Ranges", "bytes");
                H_Response.AddHeader("Accept-Ranges", "bytes");
 H_Response.Buffer = false;
                H_Response.Buffer = false;
 long Long_FileLength = File.Length;
                long Long_FileLength = File.Length;
 long Long_StartBytes = 0;
                long Long_StartBytes = 0;

 int Int_Pack = 10240;
                int Int_Pack = 10240;
 int Int_Sleep = (int)Math.Floor((float)(1000 * Int_Pack / Speed)) + 1;
                int Int_Sleep = (int)Math.Floor((float)(1000 * Int_Pack / Speed)) + 1;
 if (H_Request.Headers["Range"] != null)
                if (H_Request.Headers["Range"] != null)
 {
                {
 H_Response.StatusCode = 200;
                    H_Response.StatusCode = 200;
 string[] Str_Range = H_Request.Headers["Range"].Split(new char[] { '=', '-' });
                    string[] Str_Range = H_Request.Headers["Range"].Split(new char[] { '=', '-' });
 Long_StartBytes = Convert.ToInt64(Str_Range[1]); ;
                    Long_StartBytes = Convert.ToInt64(Str_Range[1]); ;
 }
                }
 H_Response.AddHeader("Content-Length", (Long_FileLength - Long_StartBytes).ToString());
                H_Response.AddHeader("Content-Length", (Long_FileLength - Long_StartBytes).ToString());
 if (Long_StartBytes != 0)
                if (Long_StartBytes != 0)
 {
                {
 H_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", Long_StartBytes, Long_FileLength - 1, Long_FileLength));
                    H_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", Long_StartBytes, Long_FileLength - 1, Long_FileLength));
 }
                }
 H_Response.AddHeader("Connection", "Keep-Alive");
                H_Response.AddHeader("Connection", "Keep-Alive");
 H_Response.ContentType = "application/octet-stream";
                H_Response.ContentType = "application/octet-stream";
 H_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                H_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));

 BR.BaseStream.Seek(Long_StartBytes, SeekOrigin.Begin);
                BR.BaseStream.Seek(Long_StartBytes, SeekOrigin.Begin);
 int maxCount = (int)Math.Floor((float)((Long_FileLength - Long_StartBytes) / Int_Pack)) + 1;
                int maxCount = (int)Math.Floor((float)((Long_FileLength - Long_StartBytes) / Int_Pack)) + 1;
 for (int i = 0; i < maxCount; i++)
                for (int i = 0; i < maxCount; i++)
 {
                {
 if (H_Response.IsClientConnected)
                    if (H_Response.IsClientConnected)
 {
                    {
 H_Response.BinaryWrite(BR.ReadBytes(Int_Pack));
                        H_Response.BinaryWrite(BR.ReadBytes(Int_Pack));
 Thread.Sleep(Int_Sleep);
                        Thread.Sleep(Int_Sleep);
 }
                    }
 else
                    else
 {
                    {
 i = maxCount;
                        i = maxCount;
 }
                    }
 }
                }
 }
            }
 catch
            catch
 {
            {
 return false;
                return false;
 }
            }
 finally
            finally
 {
            {
 BR.Close();
                BR.Close();
 File.Close();
                File.Close();
 }
            }
 return true;
            return true;
 }
        }
 catch
        catch
 {
        {
 return false;
            return false;
 }
        }
 }
    }
 }
}
 
 using System;
using System;
 using System.Data;
using System.Data;
 using System.Configuration;
using System.Configuration;
 using System.Web;
using System.Web;
 using System.Web.Security;
using System.Web.Security;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls;
 using System.IO;
using System.IO;
 using Excel = Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

 /// <summary>
/// <summary>
 /// SavaExcelsToServer 是把多个表保存在多个sheet中
/// SavaExcelsToServer 是把多个表保存在多个sheet中
 /// </summary>
/// </summary>
 public class SavaExcelsToServer
public class SavaExcelsToServer
 {
{
 private string m_strDirectory;//Excel文件夹
    private string m_strDirectory;//Excel文件夹
 private string m_strFileName;//Excel文件名
    private string m_strFileName;//Excel文件名
 private object[] m_ColumnHead;//表列头对象
    private object[] m_ColumnHead;//表列头对象
 private DataTable[] m_dataTable;//导入Excel的表
    private DataTable[] m_dataTable;//导入Excel的表

 /// <summary>
    /// <summary>
 /// 构造函数
    /// 构造函数
 /// </summary>
    /// </summary>
 /// <param name="strDirectory">存Excel的文件夹路径</param>
    /// <param name="strDirectory">存Excel的文件夹路径</param>
 /// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param>
    /// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param>
 /// <param name="strColName">列头名数组</param>
    /// <param name="strColName">列头名数组</param>
 public SavaExcelsToServer(string strDirectory, string strFileName, DataTable[] dataTable)
    public SavaExcelsToServer(string strDirectory, string strFileName, DataTable[] dataTable)
 {
    {
 m_strDirectory = strDirectory;
        m_strDirectory = strDirectory;
 m_strFileName = strFileName;
        m_strFileName = strFileName;
 m_dataTable = dataTable;
        m_dataTable = dataTable;
 
        
 if (!System.IO.Directory.Exists(m_strDirectory))
        if (!System.IO.Directory.Exists(m_strDirectory))
 {
        {
 Directory.CreateDirectory(m_strDirectory);
            Directory.CreateDirectory(m_strDirectory);
 }
        }
 if (File.Exists(Path.Combine(m_strDirectory, m_strFileName)))
        if (File.Exists(Path.Combine(m_strDirectory, m_strFileName)))
 {
        {
 File.Delete(m_strDirectory + "\\" + m_strFileName);
            File.Delete(m_strDirectory + "\\" + m_strFileName);
 }
        }
 }
    }

 /// <summary>
    /// <summary>
 /// 保存Excel
    /// 保存Excel
 /// </summary>
    /// </summary>
 public bool SaveExcel()
    public bool SaveExcel()
 {
    {
 int nCount = 0;     //所有表列的记数
        int nCount = 0;     //所有表列的记数 
 int nRowCount = 0;  //行数量
        int nRowCount = 0;  //行数量
 int m_ColCount = 0; //列数量
        int m_ColCount = 0; //列数量
 int nSeries = 0;    //数组维数
        int nSeries = 0;    //数组维数
 string[] strColName;//表头名数组
        string[] strColName;//表头名数组

 object objValue = System.Type.Missing;
        object objValue = System.Type.Missing;
 object A1;//Excel的列头对象
        object A1;//Excel的列头对象
 object H1;//Excel的列头对象
        object H1;//Excel的列头对象
 object A2;//Excel的行对象
        object A2;//Excel的行对象
 object H2;//Excel的行对象
        object H2;//Excel的行对象
 Excel.Application EApp;
        Excel.Application EApp;

 nSeries = m_dataTable.Length;
        nSeries = m_dataTable.Length;
 EApp = new Excel.ApplicationClass();
        EApp = new Excel.ApplicationClass();

 if (EApp == null)
        if (EApp == null)
 {
        {
 Console.WriteLine("不能打开Excel。");
            Console.WriteLine("不能打开Excel。");
 return false;
            return false;
 }
        }
 else
        else
 {
        {
 Excel.Workbooks xlWookBooks = EApp.Workbooks;
            Excel.Workbooks xlWookBooks = EApp.Workbooks;
 Excel.Workbook xlWorkBook = xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls
            Excel.Workbook xlWorkBook = xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls     
 Excel.Sheets xlSheets = xlWorkBook.Worksheets;
            Excel.Sheets xlSheets = xlWorkBook.Worksheets;
 
          
 for (int i = 0; i < nSeries; i++)
            for (int i = 0; i < nSeries; i++)
 {
            {
 nRowCount = m_dataTable[i].Rows.Count;
                nRowCount = m_dataTable[i].Rows.Count;
 m_ColCount = m_dataTable[i].Columns.Count;
                m_ColCount = m_dataTable[i].Columns.Count;
 m_ColumnHead = new object[m_ColCount];
                m_ColumnHead = new object[m_ColCount];
 strColName = new string[m_ColCount];
                strColName = new string[m_ColCount];
 for (int j = 0; j < m_ColCount; j++)
                for (int j = 0; j < m_ColCount; j++)
 {
                {
 try { strColName[j] = m_dataTable[i].Columns[j].Caption; }
                    try { strColName[j] = m_dataTable[i].Columns[j].Caption; }
 catch { strColName[j] = string.Empty; }
                    catch { strColName[j] = string.Empty; }
 }
                }
 
               
 Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlSheets.Add(Type.Missing, xlSheets[i + 1], Type.Missing, Type.Missing);
                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlSheets.Add(Type.Missing, xlSheets[i + 1], Type.Missing, Type.Missing);
 xlWorkSheet.Name = m_dataTable[i].TableName;
                xlWorkSheet.Name = m_dataTable[i].TableName;

 //对象变量初始化
                //对象变量初始化
 A1 = xlWorkSheet.Cells[1, 1];
                A1 = xlWorkSheet.Cells[1, 1];
 H1 = xlWorkSheet.Cells[1, m_ColCount];
                H1 = xlWorkSheet.Cells[1, m_ColCount];
 A2 = xlWorkSheet.Cells[2, 1];
                A2 = xlWorkSheet.Cells[2, 1];
 H2 = xlWorkSheet.Cells[2, m_ColCount];
                H2 = xlWorkSheet.Cells[2, m_ColCount];

 Excel.Range Range = xlWorkSheet.get_Range(A1, H1);
                Excel.Range Range = xlWorkSheet.get_Range(A1, H1);
 Range.Columns.HorizontalAlignment = 3;//value 水平居中
                Range.Columns.HorizontalAlignment = 3;//value 水平居中

 //设置Excle的表头
                //设置Excle的表头

 for (int k = 0; k < m_ColCount; k++)
                for (int k = 0; k < m_ColCount; k++)
 {
                {
 try { m_ColumnHead[k] = (object)strColName[k]; }
                    try { m_ColumnHead[k] = (object)strColName[k]; }
 catch { m_ColumnHead[k] = (object)string.Empty; }
                    catch { m_ColumnHead[k] = (object)string.Empty; }
 }
                }
 Range.Value2 = m_ColumnHead;
                Range.Value2 = m_ColumnHead;
 Range.Interior.ColorIndex = 0;
                Range.Interior.ColorIndex = 0;

 //向Excel中写入数据
                //向Excel中写入数据
 Range = xlWorkSheet.get_Range(A2, H2);
                Range = xlWorkSheet.get_Range(A2, H2);
 object[,] ColumnData = new object[nRowCount, m_ColCount];
                object[,] ColumnData = new object[nRowCount, m_ColCount];

 for (int n = 0; n < nRowCount; n++)
                for (int n = 0; n < nRowCount; n++)
 {
                {
 for (int j = 0; j < m_ColCount; j++)
                    for (int j = 0; j < m_ColCount; j++)
 {
                    {
 try { ColumnData[n, j] = m_dataTable[i].Rows[n][j]; }
                        try { ColumnData[n, j] = m_dataTable[i].Rows[n][j]; }
 catch { ColumnData[n, j] = string.Empty; }
                        catch { ColumnData[n, j] = string.Empty; }
 }
                    }
 }
                }
 Range = Range.get_Resize(nRowCount, m_ColCount);
                Range = Range.get_Resize(nRowCount, m_ColCount);
 Range.Value2 = ColumnData;
                Range.Value2 = ColumnData;
 //设置Excel的属性
                //设置Excel的属性
 Range.Interior.ColorIndex = 0; //设置其Excel的背景颜色
                Range.Interior.ColorIndex = 0; //设置其Excel的背景颜色
 Range.Columns.HorizontalAlignment = 3; //value 水平居中
                Range.Columns.HorizontalAlignment = 3; //value 水平居中
 Range.Cells.EntireColumn.AutoFit(); //Excel的表格宽度
                Range.Cells.EntireColumn.AutoFit(); //Excel的表格宽度
 }
            }
 Excel.Worksheet xlWorkSheet14 = (Excel.Worksheet)xlSheets[1];
            Excel.Worksheet xlWorkSheet14 = (Excel.Worksheet)xlSheets[1];
 xlWorkSheet14.Delete();
            xlWorkSheet14.Delete();
 //保存Excel文件
            //保存Excel文件
 EApp.Visible = false;
            EApp.Visible = false;
 EApp.UserControl = false;
            EApp.UserControl = false;
 EApp.DisplayAlerts = false;
            EApp.DisplayAlerts = false;
 xlWorkBook.Saved = true;
            xlWorkBook.Saved = true;
 //EApp.ActiveWorkbook.SaveCopyAs(a);
            //EApp.ActiveWorkbook.SaveCopyAs(a);
 xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName);
            xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName);
 
            
 //释放资源
            //释放资源
 xlWorkBook.Close(false, Type.Missing, Type.Missing);
            xlWorkBook.Close(false, Type.Missing, Type.Missing);
 EApp.Quit();
            EApp.Quit();
 return true;
            return true;
 }
        }
 }
    }
 }
}
 
                        
 
下面给出相应的页面部分代码,和download类和SaveExcel类。
 SaveExcel command and close view command;
SaveExcel command and close view command; using System;
using System; using System.Data;
using System.Data; using System.Configuration;
using System.Configuration; using System.Web;
using System.Web; using System.Web.Security;
using System.Web.Security; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls; using System.IO;
using System.IO; using System.Threading;
using System.Threading;
 /// <summary>
/// <summary> /// DownLoad 的摘要说明
/// DownLoad 的摘要说明 /// </summary>
/// </summary> public class DownLoad
public class DownLoad {
{ private DownLoad()
    private DownLoad() {}
    {}
 /// <summary>
    /// <summary> /// 下载函数
    /// 下载函数 /// </summary>
    /// </summary> /// <param name="H_Request">能够读取客户端在WEB请求发送期间发送的HTTP值</param>
    /// <param name="H_Request">能够读取客户端在WEB请求发送期间发送的HTTP值</param> /// <param name="H_Response">封装asp.net操作的HTTP响应信息</param>
    /// <param name="H_Response">封装asp.net操作的HTTP响应信息</param> /// <param name="FileName">文件名:aa.txt</param>
    /// <param name="FileName">文件名:aa.txt</param> /// <param name="FullPath">绝对路径:Server.MapPath("Department"+Str_FullPath)//Str_FullPath=\aa.txt</param>
    /// <param name="FullPath">绝对路径:Server.MapPath("Department"+Str_FullPath)//Str_FullPath=\aa.txt</param> /// <param name="Speed">当前线程被阻塞的毫秒数</param>
    /// <param name="Speed">当前线程被阻塞的毫秒数</param> /// <returns></returns>
    /// <returns></returns> public static bool ResponseFile(HttpRequest H_Request, HttpResponse H_Response, string FileName, string FullPath, long Speed)
    public static bool ResponseFile(HttpRequest H_Request, HttpResponse H_Response, string FileName, string FullPath, long Speed) {
    { try
        try {
        { System.IO.FileStream File = new FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
            System.IO.FileStream File = new FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); System.IO.BinaryReader BR = new BinaryReader(File);
            System.IO.BinaryReader BR = new BinaryReader(File); try
            try {
            { H_Response.AddHeader("Accept-Ranges", "bytes");
                H_Response.AddHeader("Accept-Ranges", "bytes"); H_Response.Buffer = false;
                H_Response.Buffer = false; long Long_FileLength = File.Length;
                long Long_FileLength = File.Length; long Long_StartBytes = 0;
                long Long_StartBytes = 0;
 int Int_Pack = 10240;
                int Int_Pack = 10240; int Int_Sleep = (int)Math.Floor((float)(1000 * Int_Pack / Speed)) + 1;
                int Int_Sleep = (int)Math.Floor((float)(1000 * Int_Pack / Speed)) + 1; if (H_Request.Headers["Range"] != null)
                if (H_Request.Headers["Range"] != null) {
                { H_Response.StatusCode = 200;
                    H_Response.StatusCode = 200; string[] Str_Range = H_Request.Headers["Range"].Split(new char[] { '=', '-' });
                    string[] Str_Range = H_Request.Headers["Range"].Split(new char[] { '=', '-' }); Long_StartBytes = Convert.ToInt64(Str_Range[1]); ;
                    Long_StartBytes = Convert.ToInt64(Str_Range[1]); ; }
                } H_Response.AddHeader("Content-Length", (Long_FileLength - Long_StartBytes).ToString());
                H_Response.AddHeader("Content-Length", (Long_FileLength - Long_StartBytes).ToString()); if (Long_StartBytes != 0)
                if (Long_StartBytes != 0) {
                { H_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", Long_StartBytes, Long_FileLength - 1, Long_FileLength));
                    H_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", Long_StartBytes, Long_FileLength - 1, Long_FileLength)); }
                } H_Response.AddHeader("Connection", "Keep-Alive");
                H_Response.AddHeader("Connection", "Keep-Alive"); H_Response.ContentType = "application/octet-stream";
                H_Response.ContentType = "application/octet-stream"; H_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                H_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
 BR.BaseStream.Seek(Long_StartBytes, SeekOrigin.Begin);
                BR.BaseStream.Seek(Long_StartBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((float)((Long_FileLength - Long_StartBytes) / Int_Pack)) + 1;
                int maxCount = (int)Math.Floor((float)((Long_FileLength - Long_StartBytes) / Int_Pack)) + 1; for (int i = 0; i < maxCount; i++)
                for (int i = 0; i < maxCount; i++) {
                { if (H_Response.IsClientConnected)
                    if (H_Response.IsClientConnected) {
                    { H_Response.BinaryWrite(BR.ReadBytes(Int_Pack));
                        H_Response.BinaryWrite(BR.ReadBytes(Int_Pack)); Thread.Sleep(Int_Sleep);
                        Thread.Sleep(Int_Sleep); }
                    } else
                    else {
                    { i = maxCount;
                        i = maxCount; }
                    } }
                } }
            } catch
            catch {
            { return false;
                return false; }
            } finally
            finally {
            { BR.Close();
                BR.Close(); File.Close();
                File.Close(); }
            } return true;
            return true; }
        } catch
        catch {
        { return false;
            return false; }
        } }
    } }
}
 using System;
using System; using System.Data;
using System.Data; using System.Configuration;
using System.Configuration; using System.Web;
using System.Web; using System.Web.Security;
using System.Web.Security; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls; using System.IO;
using System.IO; using Excel = Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
 /// <summary>
/// <summary> /// SavaExcelsToServer 是把多个表保存在多个sheet中
/// SavaExcelsToServer 是把多个表保存在多个sheet中 /// </summary>
/// </summary> public class SavaExcelsToServer
public class SavaExcelsToServer {
{ private string m_strDirectory;//Excel文件夹
    private string m_strDirectory;//Excel文件夹 private string m_strFileName;//Excel文件名
    private string m_strFileName;//Excel文件名 private object[] m_ColumnHead;//表列头对象
    private object[] m_ColumnHead;//表列头对象 private DataTable[] m_dataTable;//导入Excel的表
    private DataTable[] m_dataTable;//导入Excel的表
 /// <summary>
    /// <summary> /// 构造函数
    /// 构造函数 /// </summary>
    /// </summary> /// <param name="strDirectory">存Excel的文件夹路径</param>
    /// <param name="strDirectory">存Excel的文件夹路径</param> /// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param>
    /// <param name="strFileName">存Excel文件名,Excel文件一定要放到strDirectory文件夹内</param> /// <param name="strColName">列头名数组</param>
    /// <param name="strColName">列头名数组</param> public SavaExcelsToServer(string strDirectory, string strFileName, DataTable[] dataTable)
    public SavaExcelsToServer(string strDirectory, string strFileName, DataTable[] dataTable) {
    { m_strDirectory = strDirectory;
        m_strDirectory = strDirectory; m_strFileName = strFileName;
        m_strFileName = strFileName; m_dataTable = dataTable;
        m_dataTable = dataTable; 
         if (!System.IO.Directory.Exists(m_strDirectory))
        if (!System.IO.Directory.Exists(m_strDirectory)) {
        { Directory.CreateDirectory(m_strDirectory);
            Directory.CreateDirectory(m_strDirectory); }
        } if (File.Exists(Path.Combine(m_strDirectory, m_strFileName)))
        if (File.Exists(Path.Combine(m_strDirectory, m_strFileName))) {
        { File.Delete(m_strDirectory + "\\" + m_strFileName);
            File.Delete(m_strDirectory + "\\" + m_strFileName); }
        } }
    }
 /// <summary>
    /// <summary> /// 保存Excel
    /// 保存Excel /// </summary>
    /// </summary> public bool SaveExcel()
    public bool SaveExcel() {
    { int nCount = 0;     //所有表列的记数
        int nCount = 0;     //所有表列的记数  int nRowCount = 0;  //行数量
        int nRowCount = 0;  //行数量 int m_ColCount = 0; //列数量
        int m_ColCount = 0; //列数量 int nSeries = 0;    //数组维数
        int nSeries = 0;    //数组维数 string[] strColName;//表头名数组
        string[] strColName;//表头名数组
 object objValue = System.Type.Missing;
        object objValue = System.Type.Missing; object A1;//Excel的列头对象
        object A1;//Excel的列头对象 object H1;//Excel的列头对象
        object H1;//Excel的列头对象 object A2;//Excel的行对象
        object A2;//Excel的行对象 object H2;//Excel的行对象
        object H2;//Excel的行对象 Excel.Application EApp;
        Excel.Application EApp;
 nSeries = m_dataTable.Length;
        nSeries = m_dataTable.Length; EApp = new Excel.ApplicationClass();
        EApp = new Excel.ApplicationClass();
 if (EApp == null)
        if (EApp == null) {
        { Console.WriteLine("不能打开Excel。");
            Console.WriteLine("不能打开Excel。"); return false;
            return false; }
        } else
        else {
        { Excel.Workbooks xlWookBooks = EApp.Workbooks;
            Excel.Workbooks xlWookBooks = EApp.Workbooks; Excel.Workbook xlWorkBook = xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls
            Excel.Workbook xlWorkBook = xlWookBooks.Add(true);//或者根据绝对路径打开工作簿文件a.xls      Excel.Sheets xlSheets = xlWorkBook.Worksheets;
            Excel.Sheets xlSheets = xlWorkBook.Worksheets; 
           for (int i = 0; i < nSeries; i++)
            for (int i = 0; i < nSeries; i++) {
            { nRowCount = m_dataTable[i].Rows.Count;
                nRowCount = m_dataTable[i].Rows.Count; m_ColCount = m_dataTable[i].Columns.Count;
                m_ColCount = m_dataTable[i].Columns.Count; m_ColumnHead = new object[m_ColCount];
                m_ColumnHead = new object[m_ColCount]; strColName = new string[m_ColCount];
                strColName = new string[m_ColCount]; for (int j = 0; j < m_ColCount; j++)
                for (int j = 0; j < m_ColCount; j++) {
                { try { strColName[j] = m_dataTable[i].Columns[j].Caption; }
                    try { strColName[j] = m_dataTable[i].Columns[j].Caption; } catch { strColName[j] = string.Empty; }
                    catch { strColName[j] = string.Empty; } }
                } 
                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlSheets.Add(Type.Missing, xlSheets[i + 1], Type.Missing, Type.Missing);
                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlSheets.Add(Type.Missing, xlSheets[i + 1], Type.Missing, Type.Missing); xlWorkSheet.Name = m_dataTable[i].TableName;
                xlWorkSheet.Name = m_dataTable[i].TableName;
 //对象变量初始化
                //对象变量初始化 A1 = xlWorkSheet.Cells[1, 1];
                A1 = xlWorkSheet.Cells[1, 1]; H1 = xlWorkSheet.Cells[1, m_ColCount];
                H1 = xlWorkSheet.Cells[1, m_ColCount]; A2 = xlWorkSheet.Cells[2, 1];
                A2 = xlWorkSheet.Cells[2, 1]; H2 = xlWorkSheet.Cells[2, m_ColCount];
                H2 = xlWorkSheet.Cells[2, m_ColCount];
 Excel.Range Range = xlWorkSheet.get_Range(A1, H1);
                Excel.Range Range = xlWorkSheet.get_Range(A1, H1); Range.Columns.HorizontalAlignment = 3;//value 水平居中
                Range.Columns.HorizontalAlignment = 3;//value 水平居中
 //设置Excle的表头
                //设置Excle的表头
 for (int k = 0; k < m_ColCount; k++)
                for (int k = 0; k < m_ColCount; k++) {
                { try { m_ColumnHead[k] = (object)strColName[k]; }
                    try { m_ColumnHead[k] = (object)strColName[k]; } catch { m_ColumnHead[k] = (object)string.Empty; }
                    catch { m_ColumnHead[k] = (object)string.Empty; } }
                } Range.Value2 = m_ColumnHead;
                Range.Value2 = m_ColumnHead; Range.Interior.ColorIndex = 0;
                Range.Interior.ColorIndex = 0;
 //向Excel中写入数据
                //向Excel中写入数据 Range = xlWorkSheet.get_Range(A2, H2);
                Range = xlWorkSheet.get_Range(A2, H2); object[,] ColumnData = new object[nRowCount, m_ColCount];
                object[,] ColumnData = new object[nRowCount, m_ColCount];
 for (int n = 0; n < nRowCount; n++)
                for (int n = 0; n < nRowCount; n++) {
                { for (int j = 0; j < m_ColCount; j++)
                    for (int j = 0; j < m_ColCount; j++) {
                    { try { ColumnData[n, j] = m_dataTable[i].Rows[n][j]; }
                        try { ColumnData[n, j] = m_dataTable[i].Rows[n][j]; } catch { ColumnData[n, j] = string.Empty; }
                        catch { ColumnData[n, j] = string.Empty; } }
                    } }
                } Range = Range.get_Resize(nRowCount, m_ColCount);
                Range = Range.get_Resize(nRowCount, m_ColCount); Range.Value2 = ColumnData;
                Range.Value2 = ColumnData; //设置Excel的属性
                //设置Excel的属性 Range.Interior.ColorIndex = 0; //设置其Excel的背景颜色
                Range.Interior.ColorIndex = 0; //设置其Excel的背景颜色 Range.Columns.HorizontalAlignment = 3; //value 水平居中
                Range.Columns.HorizontalAlignment = 3; //value 水平居中 Range.Cells.EntireColumn.AutoFit(); //Excel的表格宽度
                Range.Cells.EntireColumn.AutoFit(); //Excel的表格宽度 }
            } Excel.Worksheet xlWorkSheet14 = (Excel.Worksheet)xlSheets[1];
            Excel.Worksheet xlWorkSheet14 = (Excel.Worksheet)xlSheets[1]; xlWorkSheet14.Delete();
            xlWorkSheet14.Delete(); //保存Excel文件
            //保存Excel文件 EApp.Visible = false;
            EApp.Visible = false; EApp.UserControl = false;
            EApp.UserControl = false; EApp.DisplayAlerts = false;
            EApp.DisplayAlerts = false; xlWorkBook.Saved = true;
            xlWorkBook.Saved = true; //EApp.ActiveWorkbook.SaveCopyAs(a);
            //EApp.ActiveWorkbook.SaveCopyAs(a); xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName);
            xlWorkBook.SaveCopyAs(m_strDirectory + "\\" + m_strFileName); 
             //释放资源
            //释放资源 xlWorkBook.Close(false, Type.Missing, Type.Missing);
            xlWorkBook.Close(false, Type.Missing, Type.Missing); EApp.Quit();
            EApp.Quit(); return true;
            return true; }
        } }
    } }
}
 
                    
                 
    
 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号