Aspose.Cells导出excel

利用Aspose.Cells导出excel

注意的问题

1、DataTable的处理

2、进行编码,便于中文名文件下载

3、别忘了Aspose.Cells.dll(可以自己在网上搜索)

public static bool DataTableToExcel2(DataTable datatable, string filepath, out string error)
{
    error = "";
    Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook();

    try
    {
        if (datatable == null)
        {
            error = "DataTableToExcel:datatable 为空";
            return false;
        }

        //为单元格添加样式
        Aspose.Cells.Style style = wb.Styles[wb.Styles.Add()];
        //设置居中
        style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
        //设置背景颜色
        style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
        style.Pattern = BackgroundType.Solid;
        style.Font.IsBold = true;

        int rowIndex = 0;
        for (int i = 0; i < datatable.Columns.Count; i++)
        {
            DataColumn col = datatable.Columns[i];
            string columnName = col.Caption ?? col.ColumnName;
            wb.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
            wb.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
        }
        rowIndex++;

        foreach (DataRow row in datatable.Rows)
        {
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                wb.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
            }
            rowIndex++;
        }

        for (int k = 0; k < datatable.Columns.Count; k++)
        {
            wb.Worksheets[0].AutoFitColumn(k, 0, 150);
        }
        wb.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);
        wb.Save(filepath);
        return true;
    }
    catch (Exception e)
    {
        error = error + " DataTableToExcel: " + e.Message;
        return false;
    }

}

protected void btnExport_Click(object sender, EventArgs e)
{//导出
    int ClassID = 0;
    int.TryParse(hidClassID.Value, out ClassID);
    string error = "";
    string filepath = "";
    BLL.TUser bll_TUser = new BLL.TUser();
    BLL.TClass bll_Class = new BLL.TClass();
    Model.TClass model = (new BLL.TClass()).GetModel(ClassID);

    //处理DataTable
    DataTable dt = bll_TUser.GetListByClass(ClassID);
    DataTable dtNew = new DataTable();
    dtNew.Columns.Add("姓名", typeof(string));
    dtNew.Columns.Add("学号", typeof(string));
    dtNew.Columns.Add("性别", typeof(string));
    dtNew.Columns.Add("电话", typeof(string));
    if (dt != null && dt.Rows.Count > 0)
    {
        DataRow drNew = dtNew.NewRow();

        foreach (DataRow dr in dt.Rows)
        {
            //drNew = dtNew.NewRow();
            drNew["姓名"] = dr["UserName"];
            drNew["学号"] = dr["IDNO"];
            drNew["性别"] = dr["Sex"].ToString() == "1" ? "男" : (dr["Sex"].ToString() == "2" ? "女" : "");
            drNew["电话"] = dr["Phone"];
            dtNew.Rows.Add(drNew.ItemArray);
        }
    }

    if (model != null)
    {
        filepath = "/UploadFiles/ExportClass/";// + model.ClassName + ".xlsx";
        string filaname = model.ClassName + ".xlsx";
        string finalPath = MapPath("~" + filepath + filaname);
        //检查有该路径是否就创建
        if (!Directory.Exists(MapPath("~/UploadFiles/ExportClass/")))
        {
            Directory.CreateDirectory(MapPath("~/UploadFiles/ExportClass/"));
        }
        if (DataTableToExcel2(dtNew, finalPath, out error))
        {
            string SiteRoot = "http://" + Request.Url.Authority.ToString() + filepath + Uri.EscapeDataString(filaname); //进行编码,便于中文名文件下载
            //下载excel
            ClientScript.RegisterStartupScript(this.GetType(), "", ",<script type=‘text/javascript‘>window.open(‘" + SiteRoot + "‘);</script>");
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script type=‘text/javascript‘>alert(‘提示‘, ‘" + error + "!‘);</script>");
        }
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script type=‘text/javascript‘>alert(‘提示‘, ‘班级不存在!‘);</script>");
    }
}

时间: 2024-10-20 09:23:46

Aspose.Cells导出excel的相关文章

Aspose.cells 导出Excel

//Export private void btnExport_Click(object sender, RoutedEventArgs e) { string strDataTime = System.DateTime.Now.ToString("yyyyMMdd_HHmmss"); string strFileName = "buyf_Template" + strDataTime; SaveFileDialog save = new SaveFileDialo

C#使用Aspose.Cells导出Excel简单实现

首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出): 1 /// <summary> 2 /// 导出Excel表格 3 /// </summary> 4 /// <param name="list">数据集合</param> 5 /// <param name="heade

extjs+Aspose.Cells导出到Excel

1.&=DataSource.Field,&=[DataSource].[Field]是对DataTable和几何类型的引用,将会从当前行开始竖直向下生成多行数据. 2.&=$data:是对变量或数组的引用.数组存在skip,horizontal等属性,具体参见官方网站 3.&=&=动态公式计算:{r}当前行,{c}当前列,{-n},{n}当前行或列的偏移量前n或后n. 4.&==是动态计算,如excel,if等语句.(if(logic_test,true_

Aspose.Cells 操作Excel相关文章

Aspose.Cells 根据Excel模板导出数据统计 使用Aspose.Cell控件实现Excel高难度报表的生成(一)

使用Aspose.Cells生成Excel的方法详解(转)

using System; using System.Collections.Generic;  using System.Linq;  using System.Web;  using System.IO;  using System.Data;  using Aspose.Cells;   /// <summary> ///OutFileDao 的摘要说明 /// </summary>  public class OutFileDao  {          public Ou

Aspose.cells 处理Excel文件

//浏览Excel文件 private void btnScan_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.DefaultExt = "xlsx"; ofd.Filter = "Excel file|*.xlsx"; if (ofd.ShowDialog() == true) { this.txtFilePath.Text = of

报表中的Excel操作之Aspose.Cells(Excel模板)

本文转载:http://www.cnblogs.com/whitewolf/archive/2011/03/21/Aspose_Cells_Template1.html 报表中的Excel操作之Aspose.Cells(Excel模板)

Aspose.Cells将Excel转成pdf

Aspose.Cells Excel转成pdf /// <summary> /// excel转pdf /// </summary> /// <param name="path">文件地址</param> /// <param name="newFilePath">转换后的文件地址</param> /// <returns></returns> public static

Asp.net &amp; Aspose.cells 导出

1 protected void btnExport_Click(object sender, EventArgs e) 2 { 3 DataTable tbBooks = (DataTable)Session["Books"]; 4 if (tbBooks == null) 5 { 6 return; 7 }13 try 14 { 15 Workbook newWorkBook = NewExcel(); 16 Aspose.Cells.Worksheet newSheet = ne