2015-08-14 3 views
0

Я использую asp.net C#, в настоящее время делаю экспорт файла excel. Я хочу экспортировать в .xlsx. все кажется прекрасным, пока я его не открою. Код ниже - мой код для экспорта.export excel не может быть открыт .xlsx

DataTable dt = GetData(sqlcommand); 

      if(dt.Rows.Count >0){ 
       //Create a dummy GridView 
       GridView GridView1 = new GridView(); 
       GridView1.AllowPaging = false; 
       GridView1.DataSource = dt; 
       GridView1.DataBind(); 

       Response.Clear(); 
       Response.Buffer = true; 
       Response.AddHeader("content-disposition", "attachment;filename=InventoryReport.xlsx"); 
       Response.ContentEncoding = System.Text.Encoding.Unicode; 
       Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); 
       Response.Charset = ""; 
       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       StringWriter sw = new StringWriter(); 
       HtmlTextWriter hw = new HtmlTextWriter(sw); 

       for (int i = 0; i < GridView1.Rows.Count; i++) 
       { 
        //Apply text style to each Row 
        GridView1.Rows[i].Attributes.Add("class", "textmode"); 
       } 
       GridView1.RenderControl(hw); 

       //style to format numbers to string 
       string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
       Response.Write(style); 
       Response.Output.Write(sw.ToString()); 
       Response.Flush(); 
       Response.End(); 

Изображение ниже - это ошибка, которую я получил после открытия файла .xlsx.

enter image description here

Я надеюсь, что кто-то может помочь в моей работе. Благодаря!! очень ценю, если бы я мог помочь мне в этом .. очень ценю!

ответ

0

использовать мой код

using OfficeOpenXml; 
using System.Data; 
namespace Managed_Leverage_BAL 
{ 
public static class ExcelExportHelper 
{ 
    public static void CreateExcelFromDataSet(this DataSet dsReportData, string strFileNameWithPath, int[] DateFormatColumnNumbers = null) 
    { 
     if (File.Exists(strFileNameWithPath)) File.Delete(strFileNameWithPath); 
     FileInfo newFile = new FileInfo(strFileNameWithPath); 
     using (ExcelPackage pck = new ExcelPackage(newFile)) 
     { 
      for (int tableIndex = 0; tableIndex < dsReportData.Tables.Count; tableIndex++) 
      { 
       DataTable tbl; 
       tbl = dsReportData.Tables[tableIndex]; 
       ExcelWorksheet ws = pck.Workbook.Worksheets.Add(dsReportData.Tables[tableIndex].TableName); 
       ws.Cells["A1"].LoadFromDataTable(tbl, true); 
       if (tableIndex == 0) 
        for (int i = 0; i < DateFormatColumnNumbers.Count(); i++) 
        { 
         using (ExcelRange col = ws.Cells[DateFormatColumnNumbers[i], 1, DateFormatColumnNumbers[i] + tbl.Rows.Count, 1]) 
         { 
          col.Style.Numberformat.Format = "dd-MMM-yyyy"; 
          col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; 
         } 
        } 
       string endHeader = "A"; 
       for (int i = 0; i < tbl.Columns.Count - 1; i++) 
       { 
        endHeader = IncrementAlphabeticCounter(endHeader); 
       } 
       using (ExcelRange rng = ws.Cells["A1:" + endHeader + "1"]) 
       { 
        rng.Style.Font.Bold = true; 
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;      //Set Pattern for the background to Solid 
        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue 
        rng.Style.Font.Color.SetColor(Color.White); 
       } 
      } 
      pck.Save(); 
     } 

    } 
    public static char[] CheckZ(char[] cCounter, int iPos) 
    { 
     if (iPos >= 0) 
     { 
      if (cCounter[iPos] >= 'Z') 
      { 
       cCounter[iPos] = 'A'; 
       if (iPos == 0) 
       { 
        char[] array = new char[cCounter.Length + 1]; 
        cCounter.CopyTo(array, 1); 
        cCounter = array; 
        cCounter[0] = 'A'; 
        return cCounter; 
       } 
       cCounter = CheckZ(cCounter, iPos - 1); 
       return cCounter; 
      } 
      cCounter[iPos] = (char)(cCounter[iPos] + '\x0001'); 
     } 
     return cCounter; 
    } 
    public static string IncrementAlphabeticCounter(string sCounter) 
    { 
     if (sCounter == "") 
     { 
      return sCounter; 
     } 
     char[] cCounter = sCounter.ToCharArray(); 
     return new string(CheckZ(cCounter, cCounter.Length - 1)); 
    } 
} 

в странице

private void Download(DataSet ds) 
    { 
      String strPath = Server.MapPath("~/Docs/") + "your path"; 
      ds.CreateExcelFromDataSet(strPath); 

     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment; filename=your file name.xlsx"); 
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
     Response.TransmitFile(strPath); 
     Response.Flush(); 
     Response.End(); 
    } 

вам потребуется DLL epplus, получить его здесь
http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=epplus&DownloadId=813458&FileTime=130743526623500000&Build=21028