C# 将Datatable的数据导出至指定的excel模板案例

       首先说一下需求,用户需要将一个报表的数据导出到指定的excel模板,再将这个excel模板发给客户,客户填写信息后,用户再使用该界面进行导入反写。主要功能为查询、导出、导入与保存。

      (1)查询功能,这个就是从数据库中查询数据再显示到gridControl1上,就不贴代码了。

      (2)导出功能,C#操作excel有很多方法,例如 Microsoft.Office.Interop.Excel  、Aspose.cells、NPOI等,我选的是引用 Microsoft.Office.Interop.Excel。注意:这个组件的索引是从1开始的!

        

        /// <summary>
        /// 导出数据至excel模板(使用Microsoft.Office.Interop.Excel组件的方式)
        /// </summary>
        public void ExportExcel(DataTable DT)
        {
            try
            {
                //需要添加 Microsoft.Office.Interop.Excel引用 
                Microsoft.Office.Interop.Excel.Application app = new                                                 
                Microsoft.Office.Interop.Excel.Application();
                if (app == null)//服务器上缺少Excel组件,需要安装Office软件
                {
                    return;
                }
                app.Visible = false;
                app.UserControl = true;
                //添加模板至项目启动的debug文件夹中
                string strTempPath = Application.StartupPath + @"\OfficeTemplate\模版.xls";
                Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
                Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加载模板
                Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
                Microsoft.Office.Interop.Excel._Worksheet worksheet =                             
               (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。
                if (worksheet == null)//工作薄中没有工作表
                {
                    return;
                }

                //1、获取数据
                int rowCount = DT.Rows.Count;
                if (rowCount < 1)//没有取到数据
                {
                    return;
                }

                //表头信息
                worksheet.Cells[5, 3] = DT.Rows[0]["日期"].ToString();
                worksheet.Cells[5, 10] = DT.Rows[0]["名称"].ToString();

                //此项目需要先插入需要的行 再进行赋值
                  object MisValue = Type.Missing;
                   for (int i = 1; i <= rowCount; i++)
                {
                    //从第八行开始新增 插入一行
                    Microsoft.Office.Interop.Excel.Range xlsRows = 
                 (Microsoft.Office.Interop.Excel.Range)worksheet.Rows[9, MisValue];
                 xlsRows.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, MisValue);

                }
             //2、写入数据,Excel索引从1开始
                for (int i = 1; i <= rowCount; i++)
                {

                    int row_ = 7 + i;  //Excel模板上表头占了1行
                    int dt_row = i - 1; //dataTable的行是从0开始的 
                    worksheet.Cells[row_, 1] = DT.Rows[dt_row]["列名1"].ToString();
                    worksheet.Cells[row_, 2] = DT.Rows[dt_row]["列名2"].ToString();
                    worksheet.Cells[row_, 3] = DT.Rows[dt_row]["列名3"].ToString();
                    worksheet.Cells[row_, 4] = DT.Rows[dt_row]["列名4"].ToString();
         

                /* 此为注释内容无需注意
                     string strNum = DT.Rows[dt_row]["数量"].ToString() == "" ? "0" : 
                    DT.Rows[dt_row]["数量"].ToString();
                    if (strNum.Contains("."))
                    {//字符串为浮点数
                        strNum = strNum.TrimEnd('0').TrimEnd('.');//1.00000
                    }
                    amount = amount + Convert.ToInt32(strNum);*/


                }

                //设置导出文件路径
                //string dir = System.Environment.CurrentDirectory;//当前工作目录完全限定
                string dir = System.Environment.SystemDirectory;//系统目录的         
                string filePath = FileDialogHelper.SaveExcel("需要填写的文件名", dir);

                if (!string.IsNullOrEmpty(filePath))
                {
                    try
                    {
                        //保存生成的Excel文件
                        workbook.SaveAs(filePath, Missing.Value, Missing.Value,                 
                        Missing.Value, Missing.Value, Missing.Value, 
                        Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, 
                        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                        Msg.ShowInformation("保存成功");
                        workbook.Close();
                    }
                    catch (Exception ex)
                    {
                        Msg.ShowException(ex);
                    }
                }

            
              }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

 

  //保存excel的类
 public class FileDialogHelper
    {
       public static string SaveExcel(string file, string path)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialDirectory = path;
           // saveFileDialog.Filter = "excel2003|*.xls|excel2007|*.xlsx";
            saveFileDialog.Filter = "excel2007|*.xls|excel2003|*.xlsx";
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = file;//文件名赋值
            saveFileDialog.FilterIndex = 1;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            return "";
        }




    }

(3)导入功能,我选择引用Aspose.cells来导入数据。注意:这个组件的索引是从0开始的!

    private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
   try
            {
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string _filePath = openFileDialog1.FileName;
                    if (_filePath != "")
                    {
                        using (FileStream fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
                        {
                            DataTable dt = Table();
                            Workbook wk = new Workbook();//工作簿
                            wk.Open(fs);  //打开excel文档
                            Worksheet worksheet = wk.Worksheets[0];//工作表
                            Cells cells = worksheet.Cells;//获取worksheet所有单元格
                            //判断excel导入格式
                            if (!cells[4, 1].StringValue.Contains("日期"))
                            {
                                MessageBox.Show("导入的文档格式不对,请选择正确格式的文档导入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            //循环遍历所有单元格信息
                            for (int i = 7; i <= cells.Rows.Count; i++)
                            {
                                if (string.IsNullOrEmpty(cells[i, 0].StringValue.Trim()))
                                {
                                    break;
                                }
                                DataRow dr = dt.NewRow();
                                dr["表头1"] = cells[4, 2].StringValue.Trim();
                                dr["表头2"] = cells[4, 5].StringValue.Trim();
                                dr["表头3"] = cells[4, 7].StringValue.Trim();
                                dr["表头4"] = cells[4, 9].StringValue.Trim();
                                dr["列名1"] = cells[i, 0].StringValue.Trim();
                                dr["列名2"] = cells[i, 1].StringValue.Trim();
                                dr["列名3"] = cells[i, 2].StringValue.Trim();
                                dr["列名4"] = cells[i, 3].StringValue.Trim();
                                
                                dt.Rows.Add(dr);
                            }
                            gridControl1.DataSource = dt;
                            gridView1.BestFitColumns();
                        }

                    }
                }
            }
            catch (Exception es)
            {
                MessageBox.Show(es.ToString());
            }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是示例代码: ```csharp using System.IO; using System.Data; using System.Text; using System.Web; using System.Web.UI; public static void ExportDataTableToExcel(DataTable dt, string fileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString()); HttpContext.Current.Response.ContentType = "application/ms-excel"; string colHeaders = "", ls_item = ""; //定义表对象与行对象,同时用DataSet对其值进行初始化 DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的 int i = 0; int cl = dt.Columns.Count; //向HTTP输出流中写入列头数据 for (i = 0; i < cl; i++) { if (i == (cl - 1)) { colHeaders += dt.Columns[i].Caption.ToString(); } else { colHeaders += dt.Columns[i].Caption.ToString() + "\t"; } } HttpContext.Current.Response.Write(colHeaders + "\n"); //逐行处理数据 foreach (DataRow row in myRow) { //在当前行中,逐列获得数据,注意行列的顺序 for (i = 0; i < cl; i++) { if (i == (cl - 1)) { ls_item += row[i].ToString(); } else { ls_item += row[i].ToString() + "\t"; } } //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 HttpContext.Current.Response.Write(ls_item + "\n"); ls_item = ""; } HttpContext.Current.Response.End(); } ``` 使用方法: ```csharp // 假设 DataTable 名为 dt,文件名为 example.xlsx ExportDataTableToExcel(dt, "example.xlsx"); ``` 这个方法会将 DataTable 中的数据导出为 .xlsx 文件,并返回给客户端下载。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值