数据从c#导出到excel

时间:2016-09-22 07:05:00

标签: c# excel

我正在尝试将数据从datatable导出到excel但是当我打开excel时,我收到了附加错误:

enter image description here

以下是我用于导出数据的代码。

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();

3 个答案:

答案 0 :(得分:1)

 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();
            }
    }

数据表是ResultsData

答案 1 :(得分:0)

问题是您没有使用任何excel组件来编写excel文件。 如果你可以使用,那么试试这个,否则你的问题的评论会有所帮助:

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();
        }
    }

答案 2 :(得分:0)

我找到了一种简单的导出方式。我只是使用CSV文件进行数据导出,并使用了编码UTF32。这有助于数据导出,任务很容易完成。