C# Excel 的导入 导出 下载

1.导入:

public DataSet LoadDataFromExcel(string filePath,HttpResponse resp)
    {
        try
        {
            string strConn;
            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
            OleDbConnection OleConn = new OleDbConnection(strConn);
            OleConn.Open();
            System.Data.DataTable dtSheetName = OleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });


            string[] strTableNames = new string[dtSheetName.Rows.Count];


            for (int k = 0; k < dtSheetName.Rows.Count; k++)
            {


                strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
            }


            String sql = "SELECT * FROM  [" + strTableNames[0] + "]";//可是更改Sheet名称,比如sheet2,等等 
            OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
            DataSet OleDsExcle = new DataSet();
            OleDaExcel.Fill(OleDsExcle, "Sheet1");
            OleConn.Close();
            return OleDsExcle;
        }
        catch 
        {
            resp.Write("<script>alert('Failed!')</script>");
            return null;
        }
    }

2.导出:

 public void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
    {


        if (File.Exists(strFileName))
          return;
       
        if (tmpDataTable == null)
        {
            return;
        }
        int rowNum = tmpDataTable.Rows.Count;
        int columnNum = tmpDataTable.Columns.Count;


        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();


        xlApp.DefaultFilePath = "";
        xlApp.DisplayAlerts = true;
        xlApp.SheetsInNewWorkbook = 1;
       // object oMissing = System.Reflection.Missing.Value;  
        Workbook xlBook = xlApp.Workbooks.Add(true);
        Worksheet xlSheet = xlBook.Worksheets[1] as Worksheet; 


        //将DataTable的列名导入Excel表第一行
        int rowIndex = 1;
        int columnIndex = 0;
        foreach (DataColumn dc in tmpDataTable.Columns)
        {
            columnIndex++;
            if (dc.ColumnName == "时间")
                xlSheet.Cells[rowIndex, columnIndex] = "周一";
            else
                xlSheet.Cells[rowIndex, columnIndex] = dc.ColumnName;


            Range rg = (Range)xlSheet.Columns[columnIndex];
            rg.NumberFormatLocal = "@";
        }


        rowIndex = 2;
        //将DataTable中的数据导入Excel中
        for (int i = 0; i < rowNum; i++)
        {
            for (int j = 0; j < columnNum; j++)
            {
                xlSheet.Cells[rowIndex + i, j + 1] = tmpDataTable.Rows[i][j].ToString();
            }
        }


        xlApp.DisplayAlerts = false;
        xlApp.AlertBeforeOverwriting = false;


        //xlBook.Save();
        xlBook.SaveAs(strFileName);
        //xlApp.SaveWorkspace(strFilePath + "Summary.xls");


        //xlBook.SaveCopyAs(strFilePath + "Summary.xls");


       
       /* xlBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing);*/
       /* System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);*/
        xlBook = null;
        //结束进程,释放资源
        xlApp.Quit();
        GC.Collect();
       
    }

3.下载文件;

public static void DownLoadFile(System.Web.UI.Page page, string fileName)
    {
        try
        {
            fileName = HttpContext.Current.Server.MapPath(fileName);
            FileInfo DownloadFile = new FileInfo(fileName); //设置要下载的文件
            page.Response.Clear();      //清除缓冲区流中的所有内容输出
            page.Response.ClearHeaders();   //清除缓冲区流中的所有头
            page.Response.Buffer = false;    //设置缓冲输出为false
            //设置输出流的 HTTP MIME 类型为application/octet-stream
            page.Response.ContentType = "application/octet-stream";
            //将 HTTP 头添加到输出流
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));
            page.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            //将指定的文件直接写入 HTTP 内容输出流
            page.Response.WriteFile(DownloadFile.FullName);
            page.Response.Flush(); //向客户端发送当前所有缓冲的输出
            //将当前所有缓冲的输出发送到客户端
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
            page.Response.End();
        }
        catch 
        {
        //错误处理
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,你可以使用 Microsoft.Office.Interop.Excel 库来实现 Excel 文件的导入导出。以下是示例代码: Excel 导入: ```csharp using Microsoft.Office.Interop.Excel; string filePath = "path/to/excel/file.xlsx"; Application excel = new Application(); Workbook workbook = excel.Workbooks.Open(filePath); Worksheet worksheet = workbook.Sheets[1]; // 读取数据 for (int i = 1; i <= worksheet.UsedRange.Rows.Count; i++) { for (int j = 1; j <= worksheet.UsedRange.Columns.Count; j++) { Range range = (Range)worksheet.Cells[i, j]; Console.Write(range.Value2.ToString() + "\t"); } Console.WriteLine(); } // 关闭连接 workbook.Close(); excel.Quit(); ``` 这个示例代码会打开名为 path/to/excel/file.xlsx 的 Excel 文件,并读取第一个工作表中的所有数据。你可以根据需要修改文件路径和工作表索引。 Excel 导出: ```csharp using Microsoft.Office.Interop.Excel; string filePath = "path/to/excel/file.xlsx"; Application excel = new Application(); Workbook workbook = excel.Workbooks.Add(); Worksheet worksheet = workbook.Sheets[1]; // 写入数据 for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 5; j++) { Range range = (Range)worksheet.Cells[i, j]; range.Value2 = i * j; } } // 保存文件 workbook.SaveAs(filePath); workbook.Close(); excel.Quit(); ``` 这个示例代码会创建一个新的 Excel 文件,并在第一个工作表中写入一些数据。你可以根据需要修改文件路径和数据。注意,使用 SaveAs 方法保存文件时需要指定文件路径和文件格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值