如何按名称设置目标工作表?

时间:2012-09-25 08:53:04

标签: c# excel silverlight

我想将一个元素(可能是gridview,List等)导出为.xls文件,并在Silverlight 4.0中通过给定字符串设置WorkSheet。 我该如何解决这个问题?

以下是使用RadGridView API的导出功能...

public RadGridView Grid { get; private set; }
void ExportWithoutDetail()
{
    SaveFileDialog saveDialog = new SaveFileDialog();
    saveDialog.Filter = ReadFilter();
    saveDialog.FilterIndex = 4;


    if (saveDialog.ShowDialog() == true)
    {
        SetAllColumnVisibile();
        Stream stream = null;
        try
        {
            using (stream = saveDialog.OpenFile())
            {
                GridViewExportOptions opt = CreateExportOptions();

                switch (saveDialog.FilterIndex)
                {
                    case 1: //*.txt
                        opt.Format = ExportFormat.Text;
                        break;
                    case 2: //*.html
                        opt.Format = ExportFormat.Html;
                        break;
                    case 3: //*.csv
                        opt.Format = ExportFormat.Csv;
                        break;
                    case 4: //*.xls
                        opt.Format = ExportFormat.ExcelML;
                        break;
                    case 5: //*.xml
                        opt.Format = ExportFormat.ExcelML;
                        break;
                }
                Grid.Export(stream, opt);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (stream != null)
                stream.Close();

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用此代码

将网格或列表导出到Excel
 if ((xamGridtemplateDet.ItemsSource).Count > 0)
        {
            Workbook wrkbook = new Workbook();

            Worksheet wrkSHT = wrkbook.Worksheets.Add("Sheet 1");

            wrkSHT.DisplayOptions.PanesAreFrozen = true;
            wrkSHT.DisplayOptions.FrozenPaneSettings.FrozenRows = 1;

            wrkSHT.DefaultColumnWidth = 5000;
            int currentcolumn = 0;
            foreach (TemplateDetailUI column in xamGridtemplateDet.ItemsSource)
            {
                if (column != null)
                {
                    SetCellValue(wrkSHT.Rows[0].Cells[currentcolumn], column.ColumnName);
                    currentcolumn++;
                }
            }


            SaveExport(wrkbook);

}

     public void SaveExport(Workbook dataworkbook)
    {
        try
        {
            bool? showDialog = this.dialog.ShowDialog();
            if (showDialog == true)
            {
                using (System.IO.Stream exportstream = dialog.OpenFile())
                {
                    dataworkbook.Save(exportstream);
                    exportstream.Close();
                }


            }
        }
        catch (Exception ex)
        {

           throw ex;
        }


    }