导出excel错误:您尝试打开FileName的文件格式与指定的扩展名不同

时间:2014-04-22 06:02:15

标签: c# asp.net .net excel visual-studio-2008

我使用以下代码将数据从数据集导出到excel文件:

 public void ExportRecords(System.Data.DataTable dt, String fileName)
    {
        try
        {
            if (dt.Rows.Count > 0)
            {
                string path = AllinAudio_Temp;
                string timestamp = Convert.ToString(DateTime.Now);
                timestamp = timestamp.Replace(" ", "");
                timestamp = timestamp.Replace("/", "");
                timestamp = timestamp.Replace(":", "");
                fileName = fileName.Replace(" ", "");

                string filename = path + @"\" + timestamp + "_" + fileName + ".xls";
                CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();

                //// Add a Worksheet with some data
                CarlosAg.ExcelXmlWriter.Worksheet sheet = book.Worksheets.Add("Sheet1");
                WorksheetStyle style = book.Styles.Add("HeaderStyle");
                style.Font.Bold = true;
                WorksheetStyle style1 = book.Styles.Add("HeaderStyle1");
                style1.Font.Bold = true;
                style1.Font.Color = "Red";

                WorksheetRow row;// = sheet.Table.Rows.Add();

                row = sheet.Table.Rows.Add();
                foreach (DataColumn column in dt.Columns)
                {
                    row.Cells.Add(new WorksheetCell(column.ColumnName, "HeaderStyle"));
                }




                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    row = sheet.Table.Rows.Add();

                    for (int l = 0; l < dt.Columns.Count; l++)
                    {
                        row.Cells.Add(dt.Rows[i][l].ToString());


                    }


                }

                book.Save(filename);
                Response.ContentType = "text/excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + timestamp + "_" + fileName + ".xls");
                Response.TransmitFile(filename);
                Response.End();


            }
        }
        catch (Exception)
        {

            throw;
        }
    }

当文件被导出并且我们尝试打开它时,它会给我消息:

enter image description here

我只想要xls格式的文件,我也用xls格式输出它。

但是当我尝试打开它时,为什么会出现这种错误。

当我尝试使用XLSX时

enter image description here

2 个答案:

答案 0 :(得分:2)

最大的提示是您用来创建文件的组件的名称。 ExcelXmlWriter似乎以Excel XML格式编写文件,文件扩展名应为XML。当您使用XLS扩展名时,Excel希望内容采用旧格式。当它无法将文件作为经典Excel文件打开时,它会尝试替代方案,发现Excel XML可以正常运行并向您发出警告。

解决方案:更改输出代码以使用文件扩展名XML而不是XLS

(如前所述,不是XLSX。)

答案 1 :(得分:1)

尝试此功能

 public static void ExportToExcelOnece(DataSet dsExcel, string ExcelFilePath)
    {

        if (dsExcel == null || dsExcel.Tables.Count == 0)
            throw new Exception("ExportToExcel: Null or empty input table!\n");

        Excel.Application excelApp = new Excel.Application();
        excelApp.Workbooks.Add();
        Excel.Worksheet newWorksheet;
        Excel.Worksheet objSheet = (Excel.Worksheet)excelApp.ActiveWorkbook.Sheets["Sheet1"];

        for (int m = 0; m <= dsExcel.Tables.Count - 1; m++)
        {
            newWorksheet = (Excel.Worksheet)excelApp.Worksheets.Add(objSheet, Missing.Value, Missing.Value, Missing.Value);
            newWorksheet.Name = dsExcel.Tables[m].TableName;

            // column headings
            for (int i = 0; i < dsExcel.Tables[m].Columns.Count; i++)
            {
                newWorksheet.Cells[1, (i + 1)] = dsExcel.Tables[m].Columns[i].ColumnName;
            }

            // rows
            for (int i = 0; i < dsExcel.Tables[m].Rows.Count; i++)
            {
                for (int j = 0; j < dsExcel.Tables[m].Columns.Count; j++)
                {
                    newWorksheet.Cells[(i + 2), (j + 1)] = dsExcel.Tables[m].Rows[i][j];
                }
            }
        }

        ((Excel.Worksheet)excelApp.ActiveWorkbook.Sheets[1]).Activate();

        objSheet.Delete();
        objSheet = (Excel.Worksheet)excelApp.ActiveWorkbook.Sheets["Sheet2"];
        objSheet.Delete();
        objSheet = (Excel.Worksheet)excelApp.ActiveWorkbook.Sheets["Sheet3"];
        objSheet.Delete();

        // check fielpath
        if (ExcelFilePath != null && ExcelFilePath != "")
        {
            try
            {
                excelApp.ActiveWorkbook.SaveAs(ExcelFilePath);
                excelApp.Quit();
                MessageBox.Show("Excel file saved!");
            }
            catch (Exception ex)
            {
                throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                    + ex.Message);
            }
        }
        else    // no filepath is given
        {
            excelApp.Visible = true;
        }


        //Quit the Application.
        excelApp.Quit();

    }