如何在microsoft.office.interop.excel中将导出格式化为excel工作簿?

时间:2015-10-14 01:13:11

标签: c# asp.net excel gridview

我有这个导出功能,允许我将2个网格视图导出到一个excel中的2个独立工作表中。

但我的问题是:

  1. 当我点击导出按钮提示用户打开,保存为,取消下载而不是将其保存到特定位置(当前我在做什么)时,如何拥有常规下载的常用弹出窗口在我的代码中)?

  2. 如何为所有单元格设置代码以启用wraptext = true,并自动格式化列高度和宽度以修复所有文本,以便它不会将######日期显示为打开excel时列宽太小的示例。

  3. protected void EXPORT_BUTTON_Click(object sender,EventArgs e)     {     Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); //在Excel应用程序中创建新的WorkBook     Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

    String DT1 = "Data table 1";
    String DT2 = "Data table 2";
    
    ExportToExcel(app, workbook, Gridview1, DT1, 1);
    
    ExportToExcel(app, workbook, Gridview2, DT2, 2);   
    
    }
    public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
    {
    
    // see the excel sheet behind the program
    app.Visible = true;
    
    // get the reference of first sheet. By default its name is Sheet1.
    // store its reference to worksheet
    
    worksheet = (Excel.Worksheet)workbook,Worksheets.Add();
    
    // changing the name of active sheet
    worksheet.Name = SheetName;
    
    // storing header part in Excel
    for (int i = 1; i < gridview.Columns.Count + 1; i++)
    {
        worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
    }
    
    
    
    // storing Each row and column value to excel sheet
    for (int i = 0; i < gridview.Rows.Count - 1; i++)
    {
        for (int j = 0; j < gridview.Columns.Count; j++)
        {
            worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
        }
    }
    //save the application
    
    workbook.SaveAs(@"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
    }
    

4 个答案:

答案 0 :(得分:1)

试试这个:

Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];

答案 1 :(得分:1)

由Laxmikant指定修改方法“ExportToExcel”的代码如下。

public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{

// see the excel sheet behind the program
app.Visible = true;

worksheet = (Excel.Worksheet)workbook.Worksheets.Add();

// changing the name of active sheet
worksheet.Name = SheetName;

// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
    worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}

// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
    for (int j = 0; j < gridview.Columns.Count; j++)
    {
        worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
    }
}

我删除了这两行代码,现在不需要参数“Sheetid”

Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
worksheet = workbook.ActiveSheet;

希望这能解决您的问题

答案 2 :(得分:1)

修改excel文件的路径以保存到虚拟路径,如下所示

workbook.SaveAs(@"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

将此更改为

workbook.SaveAs(@"~/ExcelFiles/Filename.xlsx" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

尝试使用以下代码显示另存为对话框

String FileName = "FileName.xlsx";
String FilePath = "~/ExcelFiles/FileName.xlsx"; 
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();

答案 3 :(得分:0)

您尚未在工作簿中添加工作表

尝试以下代码

worksheet =(Excel._Worksheet)oXL.Worksheets.Add();

worksheet.Name = SheetName;

了解详情http://dotnetmentors.com/c-sharp/how-to-export-sql-data-to-excel-using-microsoft-office-interop.aspx

使用rang设置标题

  string[] colNames = new string[gv.Columns.Count];

  int col = 0;

  foreach(gvvolumns dc in GridView.Columns)
    colNames[col++] = dc.ColumnName;

  char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);

  oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
  oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
  oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment 
        = Excel.XlVAlign.xlVAlignCenter;