当前位置:编程学习 > C#/ASP.NET >>

求一导出EXCEL方法

 小弟初学者,现在做一网站遇到需要把数据导出EXCEL的功能
请路过的前辈指点一个给力的方法,最好有案例源码的~ 谢谢 --------------------编程问答-------------------- http://blog.csdn.net/wonsoft/archive/2008/11/16/3311769.aspx --------------------编程问答--------------------
public void CreateExcel(DataSet ds,string typeid,string FileName) 

HttpResponse resp; 
resp = Page.Response; 
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); 
string colHeaders= "", ls_item=""; 
int i=0;

//定义表对象与行对像,同时用DataSet对其值进行初始化 
DataTable dt=ds.Tables[0]; 
DataRow[] myRow=dt.Select(""); 
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 
if(typeid=="1") 

//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 
for(i=0;i<dt.Columns.Count-1;i++)
    colHeaders+=dt.Columns[i].Caption.ToString()+"\t"; 
colHeaders +=dt.Columns[i].Caption.ToString() +"\n"; 
//向HTTP输出流中写入取得的数据信息 
resp.Write(colHeaders); 
//逐行处理数据 
foreach(DataRow row in myRow) 

//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n 
for(i=0;i<row.ItemArray.Length-1;i++)
    ls_item +=row[i].ToString() + "\t"; 
ls_item += row[i].ToString() +"\n"; 
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 
resp.Write(ls_item); 
ls_item=""; 


else 

if(typeid=="2") 

//从DataSet中直接导出XML数据并且写到HTTP输出流中 
resp.Write(ds.GetXml()); 


//写缓冲区中的数据到HTTP头文件中 
resp.End();


}


百度下一堆堆的。 --------------------编程问答-------------------- 打开EXCEL模板
gridview导出
导出XML形式
http://topic.csdn.net/u/20100805/21/5b33c048-21cc-4c78-ae08-0d5606031141.html --------------------编程问答--------------------
Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".xls");

            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.gvInfo.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
--------------------编程问答--------------------  我现在信息是用泛型集合来保存的 有直接遍历 然后保存到EXCEL的方法吗? --------------------编程问答-------------------- 可以选出建一个excel文件, 然后把excel当成数据表来处理.类似于处理access


            string filePath = Server.MapPath(@"Job_Sheet_Trims.xls");
            string newFilePath = Server.MapPath("~") + string.Format(@"\Temp\Job_Sheet_Trims_Card\Trim_{0}.xls", DateTime.Now.Ticks.ToString());
            File.Copy(filePath, newFilePath, true);
            string strConn = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Extended Properties=Excel 8.0;data source= {0}", newFilePath);
            string cmdText = "";
            using (OleDbConnection cn = new OleDbConnection(strConn))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    cmdText = "INSERT INTO [Sheet1$] ([操作], [JSNumber], [类别], [物料编号], [关联颜色], [关联尺码], [单位用量], [整批用量], [物料名称], [颜色], [尺码], [ICNumber], [Article], [Spec], [Compose], [物料种类], [需求数量], [Id]) VALUES ( '', @JSNumber, @Requisite_Type, @Item_Code, @Job_Sheet_Color_Name, @Job_Sheet_Size_Name, @Quantity, @Lot_Quantity, @Item_Name, @Item_Color, @Item_Size, @ICNumber, @Article, @Spec, @Compose, @Cat_Name, @Rq_Qty, @Id)";
                    OleDbParameter[] parms = new OleDbParameter[17];
                    parms[0] = new OleDbParameter("@JSNumber", SqlDbType.NVarChar);
                    parms[0].Value = dr["JSNumber"].ToString().Replace("'", "''");
                    parms[1] = new OleDbParameter("@Requisite_Type",SqlDbType.Int);
                    parms[1].Value = dr["Requisite_Type"].ToString();
                    parms[2] = new OleDbParameter("@Item_Code",SqlDbType.NVarChar);
                    parms[2].Value = dr["Code"].ToString().Trim();
                    parms[3] = new OleDbParameter("@Job_Sheet_Color_Name",SqlDbType.NVarChar);
                    parms[3].Value = dr["Bd_ColorName"] == null ? "" : dr["Bd_ColorName"].ToString().Replace("'", "''");
                    parms[4] = new OleDbParameter("@Job_Sheet_Size_Name",SqlDbType.NVarChar);
                    parms[4].Value = dr["JS_Co_Header"] == null ? "" : dr["JS_Co_Header"].ToString().Replace("'", "''");
                    parms[5] = new OleDbParameter("@Quantity", SqlDbType.Float);
                    parms[5].Value = dr["Quantity"] == null ? 0 : float.Parse(dr["Quantity"].ToString());
                    parms[6] = new OleDbParameter("@Lot_Quantity",SqlDbType.Float);
                    parms[6].Value = dr["Lot_Quantity"] == null ? 0 : float.Parse(dr["Lot_Quantity"].ToString());
                    parms[7] = new OleDbParameter("@Item_Name",SqlDbType.NVarChar);
                    parms[7].Value = dr["Name"] == null ? "" : dr["Name"].ToString().Replace("'", "''");
                    parms[8] = new OleDbParameter("@Item_Color",SqlDbType.NVarChar);
                    parms[8].Value = dr["Item_Color_Name"] == null ? "" : dr["Item_Color_Name"].ToString().Replace("'", "''");
                    parms[9] = new OleDbParameter("@Item_Size",SqlDbType.NVarChar);
                    parms[9].Value = dr["Item_Size_Name"] == null ? "" : dr["Item_Size_Name"].ToString().Replace("'", "''");
                    parms[10] = new OleDbParameter("@ICNumber",SqlDbType.NVarChar);
                    parms[10].Value = dr["ICNumber"] == null ? "" : dr["ICNumber"].ToString().Replace("'", "''");
                    parms[11] = new OleDbParameter("@Article",SqlDbType.NVarChar);
                    parms[11].Value = dr["ArticleNumber"] == null ? "" : dr["ArticleNumber"].ToString().Replace("'", "''");
                    parms[12] = new OleDbParameter("@Spec",SqlDbType.NVarChar);
                    parms[12].Value = dr["Spec"] == null ? "" : dr["Spec"].ToString().Replace("'", "''");
                    parms[13] = new OleDbParameter("@Compose",SqlDbType.NVarChar);
                    parms[13].Value = dr["Compose"] == null ? "" : dr["Compose"].ToString().Replace("'", "''");
                    parms[14] = new OleDbParameter("@Cat_Name",SqlDbType.NVarChar);
                    parms[14].Value = dr["Cat_Name"] == null ? "" : dr["Cat_Name"].ToString().Replace("'", "''");
                    parms[15] = new OleDbParameter("@Rq_Qty", SqlDbType.Float);
                    parms[15].Value = dr["RqQty"] == null ? 0 : float.Parse(dr["RqQty"].ToString());
                    parms[16] = new OleDbParameter("@Id", dr["Id"]);
                                      
                    OleDbCommand cmd = new OleDbCommand(cmdText, cn);
                    if (cn.State != ConnectionState.Open)
                    {
                        cn.Open();
                    }
                    foreach(OleDbParameter p in parms)
                    {
                        cmd.Parameters.Add(p);
                    }
                    cmd.ExecuteNonQuery();
                }
                cn.Dispose();
            }
--------------------编程问答-------------------- http://blog.csdn.net/xianfajushi/archive/2009/11/18/4830278.aspx --------------------编程问答--------------------
 #region //导出
    protected void BtnOUT_Click(object sender, EventArgs e)
    {
        try
        {
            string StrFileName = "JYRD";
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + StrFileName + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.ContentType = "application/ms-excel";
            StringWriter oStringWriter = new StringWriter();
            HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
            this.GvJY.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
        catch
        {
            Alert("导出出错!");
            return;
        }
    }
    #endregion

    public override void VerifyRenderingInServerForm(Control control)
    { }
--------------------编程问答-------------------- 不要求有宏的话,直接HTML导出最方便。
如下:

    private void Create()
    {
        string tableHead = @"<table width=""100%"" border=""1"" cellspacing=""0"" cellpadding=""0"">
                                    <th height=""30"" align=""center"">标题1</th>
                                    <th align=""center"">标题2</th>
                                    <th align=""center"">标题3</th>
                                    <th align=""center"">标题4</th>
                                  ";
        string td = @"<tr>
                                <td height=""28"" align=""right"">{0}</td>
                                <td align=""right"">{1}</td>
                            <td align=""right"">{2}</td>
                                <td align=""right"">{3}</td>
                            </tr>";
        string tableTail = "</table>";
        StringBuilder sb_Order = new StringBuilder();
        int i = 1;
        for (; i < 10; i++)
        {
            sb_Order.AppendFormat(td,
                                  "第" + i.ToString() + "行内容1", "第" + i.ToString() + "行内容2", "第" + i.ToString() + "行内容3", "第" + i.ToString() + "行内容4"
            );
        }
        string mFileName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
        string sf = mFileName + ".xls";

        string Content = tableHead + sb_Order.ToString() + tableTail;
        /*
        CreateFiles(HttpContext.Current.Server.MapPath(sf), Content);

        mFileName += ".xls";
        HttpResponse res = HttpContext.Current.Response;
        res.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        res.ContentType = "application/vnd.ms-excel";
        res.AppendHeader("Content-Disposition", "attachment;filename=" + mFileName);
        res.Write(Content);
        res.Redirect(sf);
        res.End();
        */
        CreateExcel(sf, "rr/" + sf, Content);
    }

    /// <summary>
    /// 生成Excel
    /// </summary>
    /// <param name="FileName">文件名</param>
    /// <param name="FilePath">相对路径包括文件名</param>
    /// <param name="ExcelContent">内容</param>
    private void CreateExcel(String FileName,String FilePath,String ExcelContent)
    {
        CreateFiles(HttpContext.Current.Server.MapPath(FilePath), ExcelContent);
        HttpResponse res = HttpContext.Current.Response;
        res.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        res.ContentType = "application/vnd.ms-excel";
        res.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
        res.Write(ExcelContent);
        res.Redirect(FilePath);
        res.End();
    }

    private bool CreateFiles(string fileurl, string str)
    {
        try
        {
            File.WriteAllText(fileurl, str);
            return true;
        }
        catch
        {
            return false;
        }
    }
--------------------编程问答-------------------- 呵呵,我今天刚做了,给你看下。首先将你的数据放到一个dataset里面或者其它里面也可以。然后用到处excel方法倒出来,具体如下,希望能解决你的问题。
private void btnCSV_Click(object sender, EventArgs e)
{
//C#创建Excel文件之取得数据  
DataTable dt = GetData();//要导出的数据放到dataset表中,
ComLibrary com = new ComLibrary();
if (dt != null)
{
SaveExcel(dt);//导出excel方法
}
}

/// <summary>
/// 创建Excel
/// </summary>
private void SaveExcel(DataTable dt)
{
//创建一个excel application  
Microsoft.Office.Interop.Excel.Application xls_exp = null;
int rowindex = 1;
int colindex = 0;
string path = "";
//创建一个workbook,一个worksheet  
Microsoft.Office.Interop.Excel.Workbook xls_book = null;
Microsoft.Office.Interop.Excel.Worksheet xls_sheet = null;
try
{
this.Cursor = Cursors.WaitCursor;
xls_exp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xls_book = xls_exp.Workbooks.Add(true);
//同样方法处理数据  
int rowidx = 0;
foreach (DataRow row in dt.Rows)
{
//首行
if (rowidx == 0)
{
colindex = 1;
xls_sheet = (Microsoft.Office.Interop.Excel.Worksheet)xls_book.ActiveSheet;
//xls_sheet.Name = "测试";
if (row["TRADEMARK"].ToString() == "")
{
xls_sheet.Name = "呵呵";
}
else
{
xls_sheet.Name = row["TRADEMARK"].ToString();
}
xls_exp.Cells[1, colindex] = "编号";
xls_exp.Cells[1, colindex + 1] = "名称";
xls_exp.Cells[1, colindex + 2] = "数量";
xls_exp.Cells[1, colindex + 3] = "库存";
}
else
{
if (row["TRADEMARK"].ToString() != dt.Rows[rowidx - 1]["TRADEMARK"].ToString())
{
rowindex = 1;
xls_exp.Sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xls_sheet = (Microsoft.Office.Interop.Excel.Worksheet)xls_book.Worksheets[1];
//xls_sheet.Name = row["TRADEMARK"].ToString();
if (row["TRADEMARK"].ToString() == "")
{
xls_sheet.Name = "无供应商";
}
else
{
xls_sheet.Name = row["TRADEMARK"].ToString();
}
colindex = 1;
xls_exp.Cells[1, colindex] = "编号";
xls_exp.Cells[1, colindex + 1] = "名称";
xls_exp.Cells[1, colindex + 2] = "数量";
xls_exp.Cells[1, colindex + 3] = "这里写dataset的列名称";
}
}
colindex = 1;
                    ////数字格式设置为文本  
                    //xls_sheet.get_Range(
                    //xls_exp.Cells[rowindex-1, colindex],
                    //xls_exp.Cells[rowindex-1, colindex + 3]).NumberFormatLocal = "@";

rowindex++;
//C#创建Excel文件之给cell赋值  
                    //数字格式设置为文本  
                    xls_sheet.get_Range(xls_exp.Cells[rowindex, colindex], xls_exp.Cells[rowindex, colindex + 1]).NumberFormatLocal = "@";
                    xls_exp.Cells[rowindex, colindex] =  row["ITEMCD"] ;
xls_exp.Cells[rowindex, colindex + 1] = row["ITEMNAME"];
xls_exp.Cells[rowindex, colindex + 2] = row["SALEQTY"];
xls_exp.Cells[rowindex, colindex + 3] = row["QTY"];
rowidx++;
}
this.Cursor = Cursors.Default;

string filename;
if (ComLibrary.GetRadioButton(pnlList) == "4")//其他报表
{
if (ComLibrary.ToInt(dtpStartDate.txtDate.Text) != ComLibrary.ToInt(dtpEndDate.txtDate.Text))
{
filename = (ComLibrary.ToInt(dtpStartDate.txtDate.Text)).ToString("####年##月##日")
+ (ComLibrary.ToInt(dtpEndDate.txtDate.Text)).ToString(" 至 ####年##月##日销售报表") + ".xls";
}
else
{//考虑到可以打印过去某日的报表
filename = (ComLibrary.ToInt(dtpEndDate.txtDate.Text)).ToString("####年##月##日报表") + ".xls";
}
}
else
{
filename = DateTime.Now.ToString("yyyy年MM月dd日") + "报表.xls";
}
saveFileDialog1.FileName = filename;
//saveFileDialog1.Filter = "Excel文档|.xls";
saveFileDialog1.Title = "存放位置";
saveFileDialog1.Filter = "excel files(*.xls)|*.xls";//excel files(*.xls)|*.xls|All files(*.*)|*.* 
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
path = saveFileDialog1.FileName;
//放弃保存
this.Cursor = Cursors.Default;
//不替换时关闭
xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
return;
}
path = saveFileDialog1.FileName;
xls_exp.Cells.EntireColumn.AutoFit();
xls_book.Saved = true;
xls_book.SaveCopyAs(path);
DialogResult dr = MessageBox.Show("导出成功!是否打开所在文件夹?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
System.Diagnostics.Process.Start("explorer.exe", "/select," + path);
}
this.Cursor = Cursors.Default;

xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
}
catch (Exception err)
{
//异常时关闭
xls_book.Close(false, path, Missing.Value);//关闭不保存修改
xls_exp.Application.Quit();
xls_exp.Quit();
GC.Collect();
MessageBox.Show("销保存失败!(" + err.ToString() + ")", "系统信息",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
this.Cursor = Cursors.Default;
}
} --------------------编程问答-------------------- 网上的资料太多了啊,各种导出的方法都有,可以去cnblogs上搜。 --------------------编程问答-------------------- 网上很多的。。。。。 --------------------编程问答-------------------- 实在不行了去看下NPOI吧.
--------------------编程问答-------------------- 我知道能说这种东西,网上太多了,我博客里都有一个呢,自己写的 --------------------编程问答--------------------  private void btnCSV_Click(object sender, EventArgs e)
        {
            btnPrint.Focus();
            if (!ScreenCheck()) return;
            clsSale cs = new clsSale();
            clsParameter cp = new clsParameter();
            DataTable a = new DataTable();
            DataSet ds = new DataSet();
            cs.itemcd = txtItemCD.Value;
            //cs.typecd = txtTypeCD.Value;
            cs.trademark = cmbTradeMark.Value;//add by hu 20100720 商标

            switch (ComLibrary.GetRadioButton(pnlList)) //add by hu 20100705
            {
                case "0": //
                    switch (ComLibrary.GetRadioButton(pnlPrintType))
                    {
                        case "0": //                            int rtn = 0;
                            rtn = cp.GetdataDetail(1);
                            if (rtn == ComConst.FAILED)
                            {
                                ComLibrary.getMsg(cp.sqlmsg, "E", "错误");
                                return;
                            }
                            if (ComLibrary.GetRadioButton(pnlType) == "0")  //                            {
                                if (cp.num1 == 0)
                                {
                                    ds = cs.GetDataList(10);//
                                }
                                if (cp.num1 == 1)
                                {
                                    ds = cs.GetDataList(12);//
                                }
                            }
                            if (ComLibrary.GetRadioButton(pnlType) == "1")  //                            {
                                ds = cs.GetDataList(11);
                            }

                            if (ds.Tables[0].Rows.Count == 0)
                            {
                                lblMsg.Text = cm.GetMessage("E00009");
                                lblMsg.ForeColor = Color.Red;
                                return;
                            }

                            break;
                        case "1": //
                            if (ComLibrary.GetRadioButton(pnlType) == "0")  //
                            {
                                ds = cs.GetDataList(12);//
                            }
                            if (ComLibrary.GetRadioButton(pnlType) == "1")  //                            {
                                ds = cs.GetDataList(11);
                            }

                            if (ds.Tables[0].Rows.Count == 0)
                            {
                                lblMsg.Text = cm.GetMessage("E00009");
                                lblMsg.ForeColor = Color.Red;
                                return;
                            }


                            break;
                        case "2": //

                            if (ComLibrary.GetRadioButton(pnlType) == "0")  //
                            {
                                ds = cs.GetDataList(12);//
                            }
                            if (ComLibrary.GetRadioButton(pnlType) == "1")  //                            {
                                ds = cs.GetDataList(11);
                            }

                            if (ds.Tables[0].Rows.Count == 0)
                            {
                                lblMsg.Text = cm.GetMessage("E00009");
                                lblMsg.ForeColor = Color.Red;
                                return;
                            }

                            break;
                        case "3": //

                            if (ComLibrary.GetRadioButton(pnlType) == "0")  //                         {
                                ds = cs.GetDataList(16);//
                            }
                            if (ComLibrary.GetRadioButton(pnlType) == "1")  //                            {
                                ds = cs.GetDataList(11);
                            }
                            if (ds.Tables[0].Rows.Count == 0)
                            {
                                lblMsg.Text = cm.GetMessage("E00009");
                                lblMsg.ForeColor = Color.Red;
                                return;
                            }

                            break;
                            
                    }
                    break;
            }
            //C#创建Excel文件之取得数据  
            a = ds.Tables[0];
            ComLibrary com = new ComLibrary();
            if (a != null)
            {
                SaveExcel(a);
            }
        } --------------------编程问答--------------------  /// <summary>
        /// 创建Excel
        /// </summary>
        private void SaveExcel(DataTable dt)
        {
            //创建一个excel application  
            Microsoft.Office.Interop.Excel.Application xls_exp = null;
            int rowindex = 1;
            int colindex = 0;
            string path = "";
            //创建一个workbook,一个worksheet  
            Microsoft.Office.Interop.Excel.Workbook xls_book = null;
            Microsoft.Office.Interop.Excel.Worksheet xls_sheet = null;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                xls_exp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                xls_book = xls_exp.Workbooks.Add(true);
                //同样方法处理数据  
                int rowidx = 0;
                foreach (DataRow row in dt.Rows)
                {
                    //首行
                    if (rowidx == 0)
                    {
                        colindex = 1;
                        xls_sheet = (Microsoft.Office.Interop.Excel.Worksheet)xls_book.ActiveSheet;
                       //根据条件显示列名称
                        if (rdoOrderSale.Checked==true)
                        {
                            xls_exp.Cells[1, colindex] = "公司名称";
                            xls_exp.Cells[1, colindex + 1] = "商品编号";
                            xls_exp.Cells[1, colindex + 2] = "商品名称";
                            xls_exp.Cells[1, colindex + 3] = "销售价格";
                            xls_exp.Cells[1, colindex + 4] = "折扣";
                            xls_exp.Cells[1, colindex + 5] = "实际进价";
                        }
                        if (rdoOrder.Checked==true)
                        {
                            xls_exp.Cells[1, colindex] = "公司名称";
                            xls_exp.Cells[1, colindex + 1] = "商品编号";
                            xls_exp.Cells[1, colindex + 2] = "商品名称";
                            xls_exp.Cells[1, colindex + 3] = "实际进价";
                            xls_exp.Cells[1, colindex + 4] = "折扣";
                        }
                        if (radioButton2.Checked==true)
                        {
                            xls_exp.Cells[1, colindex] = "公司名称";
                            xls_exp.Cells[1, colindex + 1] = "商品编号";
                            xls_exp.Cells[1, colindex + 2] = "商品名称";
                            xls_exp.Cells[1, colindex + 3] = "销售价格";
                            xls_exp.Cells[1, colindex + 4] = "折扣";
                        }
                        if (radioButton1.Checked == true)
                        {
                            xls_exp.Cells[1, colindex] = "公司名称";
                            xls_exp.Cells[1, colindex + 1] = "商品编号";
                            xls_exp.Cells[1, colindex + 2] = "商品名称";
                        }
                    }
                   
                    colindex = 1;
                   

                    rowindex++;
                    //C#创建Excel文件之给cell赋值  
                    //根据条件显示数据
                    xls_sheet.get_Range(xls_exp.Cells[rowindex, colindex], xls_exp.Cells[rowindex, colindex + 1]).NumberFormatLocal = "@";
                    if (rdoOrderSale.Checked == true)
                    {
                        xls_exp.Cells[rowindex, colindex] = row["COMPANY"];
                        xls_exp.Cells[rowindex, colindex + 1] = row["ITEMCD"];
                        xls_exp.Cells[rowindex, colindex + 2] = row["ITEMNAME"];
                        xls_exp.Cells[rowindex, colindex + 3] = row["PRICE"];
                        xls_exp.Cells[rowindex, colindex + 4] = row["DISCOUNT"];
                        xls_exp.Cells[rowindex, colindex + 5] = row["PRICE1"];
                    }
                    if (rdoOrder.Checked == true)
                    {
                        xls_exp.Cells[rowindex, colindex] = row["COMPANY"];
                        xls_exp.Cells[rowindex, colindex + 1] = row["ITEMCD"];
                        xls_exp.Cells[rowindex, colindex + 2] = row["ITEMNAME"];
                        xls_exp.Cells[rowindex, colindex + 3] = row["PRICE1"];
                        xls_exp.Cells[rowindex, colindex + 4] = row["DISCOUNT"];
                    }
                    if (radioButton2.Checked == true)
                    {
                        xls_exp.Cells[rowindex, colindex] = row["COMPANY"];
                        xls_exp.Cells[rowindex, colindex + 1] = row["ITEMCD"];
                        xls_exp.Cells[rowindex, colindex + 2] = row["ITEMNAME"];
                        xls_exp.Cells[rowindex, colindex + 3] = row["PRICE"];
                        xls_exp.Cells[rowindex, colindex + 4] = row["DISCOUNT"];
                    }
                    if (radioButton1.Checked == true)
                    {
                        xls_exp.Cells[rowindex, colindex] = row["COMPANY"];
                        xls_exp.Cells[rowindex, colindex + 1] = row["ITEMCD"];
                        xls_exp.Cells[rowindex, colindex + 2] = row["ITEMNAME"];
                    }
                    
                    
                    rowidx++;
                }
                this.Cursor = Cursors.Default;

                string filename;
                if (ComLibrary.GetRadioButton(pnlList) == "4")//其他报表
                {

                    filename = (ComLibrary.ToInt(dtpDate.txtDate.Text)).ToString("####年##月##日报表") + ".xls";

                }
                else
                {
                    filename = DateTime.Now.ToString("yyyy年MM月dd日") + "报表.xls";
                }
                saveFileDialog1.FileName = filename;
                //saveFileDialog1.Filter = "Excel文档|.xls";
                saveFileDialog1.Title = "报表存放位置";
                saveFileDialog1.Filter = "excel files(*.xls)|*.xls";//excel files(*.xls)|*.xls|All files(*.*)|*.* 
                saveFileDialog1.FilterIndex = 0;
                saveFileDialog1.RestoreDirectory = true;

                if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
                {
                    path = saveFileDialog1.FileName;
                    //放弃保存
                    this.Cursor = Cursors.Default;
                    //不替换时关闭
                    xls_book.Close(false, path, Missing.Value);//关闭不保存修改
                    xls_exp.Application.Quit();
                    xls_exp.Quit();
                    GC.Collect();
                    return;
                }
                path = saveFileDialog1.FileName;
                xls_exp.Cells.EntireColumn.AutoFit();
                xls_book.Saved = true;
                xls_book.SaveCopyAs(path);
                DialogResult dr = MessageBox.Show("报表导出成功!是否打开报表所在文件夹?", "系统信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start("explorer.exe", "/select," + path);
                }
                this.Cursor = Cursors.Default;

                xls_book.Close(false, path, Missing.Value);//关闭不保存修改
                xls_exp.Application.Quit();
                xls_exp.Quit();
                GC.Collect();
            }
            catch (Exception err)
            {
                //异常时关闭
                xls_book.Close(false, path, Missing.Value);//关闭不保存修改
                xls_exp.Application.Quit();
                xls_exp.Quit();
                GC.Collect();
                MessageBox.Show("报表保存失败!(" + err.ToString() + ")", "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,