将数据表导出到现有 Excel

发布于 2024-12-13 15:45:33 字数 794 浏览 0 评论 0原文

我需要打开现有 Excel 文件并用数据表填充它。 我怎样才能做到这一点?

我正在 ASP.NET 中工作,

我已经尝试使用此解决方案创建 excel (http://stackoverflow.com/questions/1746701/export-datatable-to-excel-file) 然后我尝试用这样的OLEDB连接打开它,但它不起作用..它说该表的格式不正确..然后它说ir找不到ISAM文件..我不知道该怎么办..

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\reports\report.xls;Extended Properties=""Excel 8.0;HDR=No;IMEX=1""");

conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.Connection = conn;

cmd.CommandText = @"SELECT * INTO [Excel 8.0;Database=C:\reports\reportBase.xls].[SheetBase1] FROM Sheet1]";

cmd.ExecuteNonQuery();
conn.Close();

请帮助我!我很绝望!!

谢谢你!!

I need to open an existing Excel file and fill it with a DataTable.
How can I do that?

I am working in ASP.NET

I have already tried to create an excel with this solution (http://stackoverflow.com/questions/1746701/export-datatable-to-excel-file)
and then I tried to open it with an OLEDB connection like this, but it didn't work.. it said that the table was not in a correct format.. and then it said that ir couldn't find the ISAM file.. I don't know what to do..

System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\reports\report.xls;Extended Properties=""Excel 8.0;HDR=No;IMEX=1""");

conn.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.Connection = conn;

cmd.CommandText = @"SELECT * INTO [Excel 8.0;Database=C:\reports\reportBase.xls].[SheetBase1] FROM Sheet1]";

cmd.ExecuteNonQuery();
conn.Close();

Please help me!! I'm desperate!!

Thank you!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韬韬不绝 2024-12-20 15:45:33

如果您也对第 3 方 Excel .NET 库感兴趣,您可以打开现有 Excel 文件并使用 GemBox.Spreadsheet Excel C# / VB.NET 库。

下面是一个 Excel ASP.NET 示例,如何打开现有的 Excel 文件、用 DataTable 填充它并将其流式传输到浏览器:

DataTable people = (DataTable)Session["people"];

// Open excel file and insert data table.
ExcelFile ef = new ExcelFile();
ef.LoadXls(Server.MapPath("MyData.xls"));
ExcelWorksheet ws = ef.Worksheets[0];
ws.InsertDataTable(people, "A1", true);

Response.Clear();

// Stream file to browser, in required type.
switch (this.RadioButtonList1.SelectedValue)
{
    case "XLS":
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xls");
        ef.SaveXls(Response.OutputStream);
        break;

    case "XLSX":
        Response.ContentType = "application/vnd.openxmlformats";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xlsx");
        // With XLSX it is a bit more complicated as MS Packaging API
        // can't write directly to Response.OutputStream.
        // Therefore we use temporary MemoryStream.
        MemoryStream ms = new MemoryStream();
        ef.SaveXlsx(ms)
        ms.WriteTo(Response.OutputStream);
        break;
}
Response.End();

if you are also interested in 3rd party Excel .NET libraries, you can open existing Excel file and fill it with a DataTable with GemBox.Spreadsheet Excel C# / VB.NET library.

Here is an Excel ASP.NET sample how to open existing Excel file, fill it with a DataTable and stream it to browser:

DataTable people = (DataTable)Session["people"];

// Open excel file and insert data table.
ExcelFile ef = new ExcelFile();
ef.LoadXls(Server.MapPath("MyData.xls"));
ExcelWorksheet ws = ef.Worksheets[0];
ws.InsertDataTable(people, "A1", true);

Response.Clear();

// Stream file to browser, in required type.
switch (this.RadioButtonList1.SelectedValue)
{
    case "XLS":
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xls");
        ef.SaveXls(Response.OutputStream);
        break;

    case "XLSX":
        Response.ContentType = "application/vnd.openxmlformats";
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
             "Report.xlsx");
        // With XLSX it is a bit more complicated as MS Packaging API
        // can't write directly to Response.OutputStream.
        // Therefore we use temporary MemoryStream.
        MemoryStream ms = new MemoryStream();
        ef.SaveXlsx(ms)
        ms.WriteTo(Response.OutputStream);
        break;
}
Response.End();
天涯离梦残月幽梦 2024-12-20 15:45:33

您可以使用此解决方案......只有在将数据放入数据表后......

 protected void Button1_Click(object sender, EventArgs e)
 {
     DataTable dtRecords = new DataTable();
     dtRecords.Columns.Add("FIRSTNAME");
     dtRecords.Columns.Add("LASTNAME");
     dtRecords.Columns.Add("JOB");
     DataRow rw1 = dtRecords.NewRow();
     rw1[0] = "JHON";
     rw1[1] = "SMITH";
     rw1[2] = "MANAGER";
     dtRecords.Rows.Add(rw1);
     DataRow rw2 = dtRecords.NewRow();
     rw2[0] = "MICH";
     rw2[1] = "KEN";
     rw2[2] = "SR MANAGER";
     dtRecords.Rows.Add(rw2);

     UploadDataTableToExcel(dtRecords);

}
protected void UploadDataTableToExcel(DataTable dtRecords)
{
        string XlsPath = Server.MapPath(@"~/Add_data/test.xls");
        string attachment = string.Empty;
        if (XlsPath.IndexOf("\\") != -1)
        {
            string[] strFileName = XlsPath.Split(new char[] { '\\' });
            attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
        }
        else
            attachment = "attachment; filename=" + XlsPath;
        try
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = string.Empty;

            foreach (DataColumn datacol in dtRecords.Columns)
            {
                Response.Write(tab + datacol.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");

            foreach (DataRow dr in dtRecords.Rows)
            {
                tab = "";
                for (int j = 0; j < dtRecords.Columns.Count; j++)
                {
                    Response.Write(tab + Convert.ToString(dr[j]));
                    tab = "\t";
                }

                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
        }
}

you can use this solution ....Only after getting your data into the datatable....

 protected void Button1_Click(object sender, EventArgs e)
 {
     DataTable dtRecords = new DataTable();
     dtRecords.Columns.Add("FIRSTNAME");
     dtRecords.Columns.Add("LASTNAME");
     dtRecords.Columns.Add("JOB");
     DataRow rw1 = dtRecords.NewRow();
     rw1[0] = "JHON";
     rw1[1] = "SMITH";
     rw1[2] = "MANAGER";
     dtRecords.Rows.Add(rw1);
     DataRow rw2 = dtRecords.NewRow();
     rw2[0] = "MICH";
     rw2[1] = "KEN";
     rw2[2] = "SR MANAGER";
     dtRecords.Rows.Add(rw2);

     UploadDataTableToExcel(dtRecords);

}
protected void UploadDataTableToExcel(DataTable dtRecords)
{
        string XlsPath = Server.MapPath(@"~/Add_data/test.xls");
        string attachment = string.Empty;
        if (XlsPath.IndexOf("\\") != -1)
        {
            string[] strFileName = XlsPath.Split(new char[] { '\\' });
            attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
        }
        else
            attachment = "attachment; filename=" + XlsPath;
        try
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = string.Empty;

            foreach (DataColumn datacol in dtRecords.Columns)
            {
                Response.Write(tab + datacol.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");

            foreach (DataRow dr in dtRecords.Rows)
            {
                tab = "";
                for (int j = 0; j < dtRecords.Columns.Count; j++)
                {
                    Response.Write(tab + Convert.ToString(dr[j]));
                    tab = "\t";
                }

                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception ex)
        {
            //Response.Write(ex.Message);
        }
}
牛↙奶布丁 2024-12-20 15:45:33

如果您也对第 3 方 Excel .NET 库感兴趣,您可以打开现有 Excel 文件并使用 GemBox.Spreadsheet Excel C# / VB.NET 库将其填充为数据表。

或者,如果您不想花费 480 美元购买许可证,则可以完全免费下载我的 Export to Excel C# 课程。

它使用 OpenXML 库创建真正的 Excel 2007 文件,您只需指定文件名,然后调用“CreateExcelDocument”函数。

DataSet ds = CreateSampleData();
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);

您可以从数据集、数据表或列表创建 Excel 文件。

我的网页上完全免费提供了所有源代码以及说明和演示项目:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

甚至还有一些示例代码,展示了如何在 ASP.Net 应用程序中创建 Excel 文件,然后打开 它。

祝你好运 !

if you are also interested in 3rd party Excel .NET libraries, you can open existing Excel file and fill it with a DataTable with GemBox.Spreadsheet Excel C# / VB.NET library.

Alternatively, if you don't want to spend $480 on a license, you can download my Export to Excel C# class completely free of charge.

It uses the OpenXML libraries to create a real Excel 2007 file, you just have to specify a filename, and call a "CreateExcelDocument" function.

DataSet ds = CreateSampleData();
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);

You can create your Excel file from a DataSet, DataTable or List<>.

All source code is provided, absolutely free of charge, on my webpage, along with instructions and a demo project:

http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm

There's even some example code, showing how to create your Excel file in an ASP.Net app, then open it.

Good luck !

笑看君怀她人 2024-12-20 15:45:33

我通过使用这个亲爱的代码得到了准确的结果......

这可能会帮助你......

 try
        {


            if (dt == null || dt.Columns.Count == 0)
            {
                throw new Exception("ExportToExcel: Null or empty input table!\n");
            }
            string Filepath = "E:Sample\\Form.xlsx";
            string SheetName = "Elnath - 3000";
           // Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet;
           // Microsoft.Office.Interop.Excel.Range xlRange = null;
           object misValue = Type.Missing;

            Excel.Application xlApp = new Excel.Application();
           xlWorkBook = xlApp.Workbooks.Add(Filepath);

           // xlWorkBook = xlApp.Workbooks.Open(Filepath, misValue, false, misValue, misValue, misValue, true, misValue, misValue, misValue, misValue, misValue, false, misValue, misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[SheetName];

            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet;

            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets.get_Item(SheetName);
            xlWorkSheet.Activate();
           // object StartRange = "B";
          //  object EndRange = misValue;

          //  xlRange = xlWorkSheet.get_Range("A", "M");
          //  xlRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.get_Range(StartRange, misValue);

            //Header
            //for (i = 0; i < dt.Columns.Count; i++)
            //{
            //    xlRange.Cells[1, i + 1] = dt.Columns[i].ColumnName;

            //}
            //Datas
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    xlApp.Cells[i + 13, j + 1] = dt.Rows[i][j].ToString();
                }
            }
            if (Filepath != null || Filepath != "")
            {
                try
                {
                    xlApp.ActiveWorkbook.SaveAs(Filepath);
                    xlApp.Quit();

                    xlWorkSheet = null;
                    xlWorkBook = null;
                    xlApp = null;
                }
                catch (Exception ex)
                {
                    throw new Exception("Can not save file" + ex.Message);
                }
            }
            else
            {
                xlApp.Visible = true;
            }
            return dt;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

I got the accurate result by using this belove code.....

this may help you..

 try
        {


            if (dt == null || dt.Columns.Count == 0)
            {
                throw new Exception("ExportToExcel: Null or empty input table!\n");
            }
            string Filepath = "E:Sample\\Form.xlsx";
            string SheetName = "Elnath - 3000";
           // Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet;
           // Microsoft.Office.Interop.Excel.Range xlRange = null;
           object misValue = Type.Missing;

            Excel.Application xlApp = new Excel.Application();
           xlWorkBook = xlApp.Workbooks.Add(Filepath);

           // xlWorkBook = xlApp.Workbooks.Open(Filepath, misValue, false, misValue, misValue, misValue, true, misValue, misValue, misValue, misValue, misValue, false, misValue, misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[SheetName];

            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet;

            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets.get_Item(SheetName);
            xlWorkSheet.Activate();
           // object StartRange = "B";
          //  object EndRange = misValue;

          //  xlRange = xlWorkSheet.get_Range("A", "M");
          //  xlRange = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.get_Range(StartRange, misValue);

            //Header
            //for (i = 0; i < dt.Columns.Count; i++)
            //{
            //    xlRange.Cells[1, i + 1] = dt.Columns[i].ColumnName;

            //}
            //Datas
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    xlApp.Cells[i + 13, j + 1] = dt.Rows[i][j].ToString();
                }
            }
            if (Filepath != null || Filepath != "")
            {
                try
                {
                    xlApp.ActiveWorkbook.SaveAs(Filepath);
                    xlApp.Quit();

                    xlWorkSheet = null;
                    xlWorkBook = null;
                    xlApp = null;
                }
                catch (Exception ex)
                {
                    throw new Exception("Can not save file" + ex.Message);
                }
            }
            else
            {
                xlApp.Visible = true;
            }
            return dt;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文