简体   繁体   English

将数据集项目导出到Excel工作表

[英]Export dataset items to excel sheet

I am using Followin LOC for Export to and Import from Excel sheet in my asp.net application 我在我的asp.net应用程序中使用Followin LOC导出到Excel表单并从中导入

 protected void LinkbuttonExportToExcel_Click(object sender, EventArgs e)
{
    UserManager manager = new UserManager();
    DataSet dataSet = manager.GetProductDataToExport();

    string attachment = "attachment; filename=Report.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/vnd.ms-excel";
    string tab = "";
    string tab1 = "";
    foreach (DataTable table in dataSet.Tables)
    {
        foreach (DataColumn column in table.Columns)
        {
           Response.Write(tab1 + column.ColumnName);
           tab1 = "\t";
        }
    }
    tab = "\n";
        foreach (DataRow dr in dataSet.Tables[0].Rows)
    {
       for (int i = 0; i < dataSet.Tables[0].Columns.Count; i++)
        {
          Response.Write(tab + dr[i].ToString());
          tab = "\t";
        }
        tab = "\n";
    }
    Response.End();
}

protected void ButtonImportDataFromExcel_Click(object sender, EventArgs e)
{
    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/App_Data/ProductImport.xls"));
    OleDbConnection objXConn = new OleDbConnection();
    objXConn.ConnectionString = ConfigurationManager.ConnectionStrings["sqlXCon"].ConnectionString;
   if (objXConn.State == ConnectionState.Closed)
    {
        objXConn.Open();
    }

        DataTable dt = new DataTable();
        dt = objXConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string excelSheetName = string.Empty; ;
        foreach (DataRow row in dt.Rows)
        {
          excelSheetName = row["TABLE_NAME"].ToString();
        }
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" +  excelSheetName + "]", objXConn);
        OleDbDataReader rd = cmd.ExecuteReader();
        UserManager manager = new UserManager();

        while (rd.Read())
        {
            int productId = int.Parse((rd.GetValue(0).ToString()));
            string productName = (rd.GetValue(1).ToString());
            string productNameHindi = (rd.GetValue(2).ToString());
            decimal productPrice = decimal.Parse((rd.GetValue(3).ToString()));
            string productStatus = (rd.GetValue(4).ToString());
            manager.UpdateProductMasterFromExcelSheet(productId, productName);
        }
    }
    else
    {
        objXConn.Close();
    }
    msgBox1.alert("Products updated successfully");
}

} }

i am using Following connection string.. 我正在使用以下连接字符串..

<add name="sqlXCon" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source='|DataDirectory|ProductImport.xls';Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';" />

The file Report.xls exports succesfully. Report.xls文件成功导出。 But the problem is I'm not able to import "Report.xls" , unless i open the file and again save it as .xls. 但问题是我无法导入“Report.xls”,除非我打开文件并再次将其保存为.xls。 Why this is happening? 为什么会这样?

For More info abour Excel InterOp. 有关详细信息,请访问Excel InterOp。 Please refer this site.. 请参考这个网站..

Excel.Interop Excel.Interop

USE Excel Libraray, download it from http://code.google.com/p/excellibrary/downloads/list 使用Excel Libraray,从http://code.google.com/p/excellibrary/downloads/list下载

using System;
using System.Data;
using System.IO;
 using ExcelLibrary.SpreadSheet;

 namespace ExcelLibrary
 {
 /// <summary>
 /// Provides simple way to convert Excel workbook into DataSet
 /// </summary>
 public sealed class DataSetHelper
 {
/// <summary>
/// Populate all data (all converted into String) in all worksheets 
/// from a given Excel workbook.
/// </summary>
/// <param name="filePath">File path of the Excel workbook</param>
/// <returns>DataSet with all worksheet populate into DataTable</returns>
public static DataSet CreateDataSet(String filePath)
{
    DataSet ds = new DataSet();
    Workbook workbook = Workbook.Load(filePath);
    foreach (Worksheet ws in workbook.Worksheets)
    {
        DataTable dt = PopulateDataTable(ws);
        ds.Tables.Add(dt);
    }
    return ds;
}

/// <summary>
/// Populate data (all converted into String) from a given Excel 
/// workbook and also work sheet name into a new instance of DataTable.
/// Returns null if given work sheet is not found.
/// </summary>
/// <param name="filePath">File path of the Excel workbook</param>
/// <param name="sheetName">Worksheet name in workbook</param>
/// <returns>DataTable with populate data</returns>
public static DataTable CreateDataTable(String filePath, String sheetName)
{
    Workbook workbook = Workbook.Load(filePath);
    foreach (Worksheet ws in workbook.Worksheets)
    {
        if (ws.Name.Equals(sheetName))
            return PopulateDataTable(ws);
    }
    return null;
}

private static DataTable PopulateDataTable(Worksheet ws)
{
    CellCollection Cells = ws.Cells;

    // Creates DataTable from a Worksheet
    // All values will be treated as Strings
    DataTable dt = new DataTable(ws.Name);

    // Extract columns
    for (int i = 0; i <= Cells.LastColIndex; i++)
        dt.Columns.Add(Cells[0, i].StringValue, typeof(String));

    // Extract data
    for (int currentRowIndex = 1; currentRowIndex <= Cells.LastRowIndex; currentRowIndex++)
    {
        DataRow dr = dt.NewRow();
        for (int currentColumnIndex = 0; currentColumnIndex <= Cells.LastColIndex; currentColumnIndex++)
            dr[currentColumnIndex] = Cells[currentRowIndex, currentColumnIndex].StringValue;
        dt.Rows.Add(dr);
    }

    return dt;
}

/// <summary>
/// Populate all data from the given DataSet into a new Excel workbook
/// </summary>
/// <param name="filePath">File path to new Excel workbook to be created</param>
/// <param name="dataset">Source DataSet</param>
public static void CreateWorkbook(String filePath, DataSet dataset)
{
    if (dataset.Tables.Count == 0)
        throw new ArgumentException("DataSet needs to have at least one DataTable", "dataset");

    Workbook workbook = new Workbook();
    foreach (DataTable dt in dataset.Tables)
    {
        Worksheet worksheet = new Worksheet(dt.TableName);
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            // Add column header
            worksheet.Cells[0, i] = new Cell(dt.Columns[i].ColumnName);

            // Populate row data
            for (int j = 0; j < dt.Rows.Count; j++)
                worksheet.Cells[j + 1, i] = new Cell(dt.Rows[j][i]);
        }
        workbook.Worksheets.Add(worksheet);
    }
    workbook.Save(filePath);
}
 }
}

The reason this is happening is because you're not really exporting an Excel file : your LinkbuttonExportToExcel_Click generates a tab separated value file, which can be opened by Excel, but is not an Excel file. 发生这种情况的原因是因为您实际上并未导出Excel文件:您的LinkbuttonExportToExcel_Click会生成一个制表符分隔值文件,该文件可以由Excel打开,但不是Excel文件。

On the other hand, your ButtonImportDataFromExcel_Click function reads from an Excel file (which must then be a real Excel file, and not a TSV) 另一方面,ButtonImportDataFromExcel_Click函数从Excel文件中读取(必须是真正的Excel文件,而不是TSV)

So you actually have to open it manually and convert it as xls by saving it again. 所以你实际上必须手动打开它并通过再次保存将其转换为xls。

For that, you could generate your Excel file using Excel.Interop if you have Excel on your server, or use an open source library to generate your excel file. 为此,如果您的服务器上有Excel,则可以使用Excel.Interop生成Excel文件,或使用开源库生成Excel文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM