简体   繁体   中英

Data export from c# to excel

I am trying to export data from datatable to excel but when I am opening the excel I am getting the attached error :

在此处输入图片说明

Also below is the code that I am using to export data.

StreamWriter wr = new StreamWriter(@"C:\\Docs_Harshit\\file.xls");

for (int i = 0; i < dtFeeForm.Columns.Count; i++)
{
    wr.Write(dtFeeForm.Columns[i].ToString().ToUpper() + "\t");
}

wr.WriteLine();

for (int i = 0; i < (dtFeeForm.Rows.Count); i++)
{
    for (int j = 0; j < dtFeeForm.Columns.Count; j++)
    {
        if (dtFeeForm.Rows[i][j] != null)
        {
            wr.Write(Convert.ToString(dtFeeForm.Rows[i][j]) + "\t");
        }
        else
        {
            wr.Write("\t");
        }
    }                    
    wr.WriteLine();
}                
wr.Close();
 private void ExportToExl(bool firstTime)
        {
           //string path = string.Empty;               
            //Delete the file if it exists. 
            if (firstTime && File.Exists(savingFileName))
                File.Delete(savingFileName);

            if (firstTime)
            {
                //This is the first time of creating the excel file and the first sheet.
                // Create a spreadsheet document by supplying the filepath.
                // By default, AutoSave = true, Editable = true, and Type = xlsx.
                SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
                    Create(savingFileName, SpreadsheetDocumentType.Workbook);

                // Add a WorkbookPart to the document.
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                // Add a WorksheetPart to the WorkbookPart.
                var worksheetPart = workbookpart.AddNewPart<WorksheetPart>(); 
                var sheetData = new SheetData();
                worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
                var bold1 = new System.Windows.Documents.Bold();
                DocumentFormat.OpenXml.Spreadsheet.CellFormat cf = new DocumentFormat.OpenXml.Spreadsheet.CellFormat();

                // Add Sheets to the Workbook.
                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets;
                sheets = spreadsheetDocument.WorkbookPart.Workbook.
                    AppendChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>(new DocumentFormat.OpenXml.Spreadsheet.Sheets());

                // Append a new worksheet and associate it with the workbook.
                var sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.
                        GetIdOfPart(worksheetPart),
                    SheetId = sheetId,
                    Name = "Sheet" + sheetId
                };
                sheets.Append(sheet);

                //Add Header Row.
                var headerRow = new Row();
                foreach (DataColumn column in ResultsData.Columns)
                {
                    var cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) };
                    headerRow.AppendChild(cell);
                }
                sheetData.AppendChild(headerRow);

                foreach (DataRow row in ResultsData.Rows)
                {
                    var newRow = new Row();
                    foreach (DataColumn col in ResultsData.Columns)
                    {
                        var cell = new Cell
                        {
                            DataType = CellValues.String,
                            CellValue = new CellValue(row[col].ToString())
                        };
                        newRow.AppendChild(cell);
                    }
                    sheetData.AppendChild(newRow);
                }               
                workbookpart.Workbook.Save();
                spreadsheetDocument.Close();
            }
    }

Datatable is ResultsData

The issue is you are not using any excel component to write excel file. If you can use then try this otherwise the comment on your question will be helpful:

public void CreateExcelFile()
{
    //Get the data from database into datatable
    string cmdQry = "dbo.GET_Report";
    SqlCommand cmd = new SqlCommand(cmdQry);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@bySource", SqlDbType.VarChar).Value = "CLIENT".ToUpper();
    DataTable dtExcel = GetData(cmd);

    //Clears all content output from the buffer stream.  
    Response.ClearContent();
    Response.Clear();
    //Adds HTTP header to the output stream  
    Response.AddHeader("content-disposition", string.Format("attachment; filename=try.xls"));

    // Gets or sets the HTTP MIME type of the output stream  
    Response.ContentType = "application/vnd.ms-excel";
    string space = "";

    foreach (DataColumn dcolumn in dtExcel.Columns)
    {
        Response.Write(space + dcolumn.ColumnName);
        space = "\t";
    }
    Response.Write("\n");
    int countcolumn;
    foreach (DataRow dr in dtExcel.Rows)
    {
        space = "";
        for (countcolumn = 0; countcolumn < dtExcel.Columns.Count; countcolumn++)
        {
            Response.Write(space + dr[countcolumn].ToString());
            space = "\t";
        }
        Response.Write("\n");
    }
    Response.Flush();
    Response.End();
}

private DataTable GetData(SqlCommand cmd)
    {
        SqlConnection con = new SqlConnection(Bussiness.GetConnectionString("Default"));
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();

        try
        {
            con.Open();
            da.Fill(dt);
            return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            da.Dispose();
            con.Dispose();
        }
    }

I Found an easy way for exporting. I simply used CSV file for Data Export and used Encoding UTF32. That helped for data export and the task was done easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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