我可以自动将Excel文件保存在我的本地文件夹中(不要求任何保存弹出窗口)在C#Asp.Net中吗? [英] Can I Save Excel File In My Local Folder Automatically (Without Asking Any Save Popup) In C# Asp.Net ?

查看:229
本文介绍了我可以自动将Excel文件保存在我的本地文件夹中(不要求任何保存弹出窗口)在C#Asp.Net中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在c#asp.net中自动将Excel文件保存在我的本地文件夹中(不要求任何保存弹出窗口)吗?

使用以下代码在我的项目中创建和导出excel,

  public   static   void  ExportToExcel(DataTable dt, string  filename)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = ;
response.ContentType = application / download;
response.AddHeader( Content-Disposition attachment; filename = \ + filename + xls\ );
response.ContentEncoding = Encoding.Unicode;
response.BinaryWrite(Encoding.Unicode.GetPreamble());

使用(StringWriter sw = new StringWriter())
{
使用(HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.HeaderStyle.Font.Bold = true ;
dg.DataBind();
foreach (DataGridItem item in dg.Items)
{
item.Cells [ 0 ]。Style.Add(HtmlTextWriterStyle.TextAlign, );
}
dg.RenderControl(htw);
response.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true ;
HttpContext.Current.ApplicationInstance.CompleteRequest();

}
}
}





这是蠢货,但是这段代码会要求打开或保存excel文件。我不想要任何弹出窗口要求save\open。我希望代码将这个excel保存在以编程方式给出的路径中。



我该怎么做?

解决方案

< blockquote>嗨Kavitha,



在我看来,是的,你可以这样做。

只需将你的功能更改为:

  public   static   void  ExportToExcel(DataTable dt, string  filename)
{
StreamWriter wr = new StreamWriter( @ D:\\ + filename + 。xls);
尝试
{
for int i = 0 ; i < dt.Columns.Count; i ++)
{
wr.Write(dt.Columns [i] .ToString()。ToUpper()+ \t);
}

wr.WriteLine();

// 将行写入excel文件
for int i = 0 ; i < (dt.Rows.Count); i ++)
{
for int j = 0 ; j < dt。 Columns.Count; j ++)
{
if (dt.Rows [i] [j]!= null
{
wr.Write(Convert.ToString(dt.Rows [i] [j])+ \t);
}
else
{
wr.Write( \t);
}
}
// 转到下一行
wr.WriteLine();
}
// 关闭文件
wr.Close() ;
}
catch (例外情况)
{
throw ex;
}

}





然后就这样打电话:

 ExportToExcel(dt,  FileName ); 





希望这对你有用!! :) :)



问候,

Praneet






对于格式化,你必须使用互操作创建一个工作簿。



像这样:



1.)创建一个样本dt,列的新行/中断:

 System.Data.DataTable dt =  new  System.Data.DataTable(); 
DataSet ds = new DataSet();
dt.TableName = tablename;
dt.Columns.Add( 代码 typeof string ));
dt.Columns.Add( Price typeof int ));

DataRow dr = dt.NewRow();
dr [ 代码] = ABC + Environment.NewLine + QRT;
dr [ Price] = 12 ;

dt.Rows.Add(dr);

DataRow dr1 = dt.NewRow();
dr1 [ 代码] = PQR;
dr1 [ 价格] = 1 ;

dt.Rows.Add(dr1);





2.)使用Interop创建工作簿功能。

  public   static   void  CreateWorkbook(System.Data.DataTable dt, String  path)
{
int rowindex = 0 ;
int columnindex = 0 ;

Microsoft.Office.Interop.Excel.Application wapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet wsheet;
Microsoft.Office.Interop.Excel.Workbook wbook;

wapp.Visible = false ;

wbook = wapp.Workbooks.Add( true );
wsheet =(工作表)wbook.ActiveSheet;


尝试
{
for int i = 0 ; i < dt.Columns.Count; i ++)
{
wsheet.Cells [ 1 ,i + 1 ] = dt.Columns [i] .ColumnName;

}

foreach (DataRow row in dt.Rows)
{
rowindex ++;
columnindex = 0 ;
foreach (DataColumn col in dt.Columns)
{
columnindex ++;
wsheet.Cells [rowindex + 1 ,columnindex] = row [col.ColumnName];
}
}
}
catch (例外情况)
{
字符串 err = ex.Message;
}
wapp.UserControl = true ;

wbook.SaveAs( d:\\Test, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,Type.Missing,Type.Missing,
false false ,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
wbook.Close( null null );





3.)要保存文件,请调用以下函数:

< pre lang =c#> CreateWorkbook(dt, D:/);





您可以根据需要为单元格应用多种格式类型。

此外,这将自动保存,无需用户提示。



问候,

Praneet


Can i save Excel file in my local folder automatically (Without asking any save popup) in c# asp.net ?
Am using below code to create and export excel in my project,

public static void ExportToExcel(DataTable dt, string filename)
      {
          HttpResponse response = HttpContext.Current.Response;
          response.Clear();
          response.Charset = "";
          response.ContentType = "application/download";
          response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xls\"");
          response.ContentEncoding = Encoding.Unicode;
          response.BinaryWrite(Encoding.Unicode.GetPreamble());

          using (StringWriter sw = new StringWriter())
          {
              using (HtmlTextWriter htw = new HtmlTextWriter(sw))
              {
                  DataGrid dg = new DataGrid();
                  dg.DataSource = dt;
                  dg.HeaderStyle.Font.Bold = true;
                  dg.DataBind();
                  foreach (DataGridItem item in dg.Items)
                  {
                      item.Cells[0].Style.Add(HtmlTextWriterStyle.TextAlign, "left");
                  }
                  dg.RenderControl(htw);
                  response.Write(sw.ToString());
                  HttpContext.Current.Response.Flush();
                  HttpContext.Current.Response.SuppressContent = true;
                  HttpContext.Current.ApplicationInstance.CompleteRequest();

              }
          }
      }



This is wroking,but this code will ask for open or save the excel file. I do not want any popup asking save\open. I want code to save this excel in a path given programatically.

How can i do this ?

解决方案

Hi Kavitha,

In my opinion, yes you can do this.
Just change your function to this:

public static void ExportToExcel(DataTable dt, string filename)
{
    StreamWriter wr = new StreamWriter(@"D:\\" + filename + ".xls");
    try
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
        }

        wr.WriteLine();

        //write rows to excel file
        for (int i = 0; i < (dt.Rows.Count); i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (dt.Rows[i][j] != null)
                {
                    wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                }
                else
                {
                    wr.Write("\t");
                }
            }
            //go to next line
            wr.WriteLine();
        }
        //close file
        wr.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}



And then just call it like this:

ExportToExcel(dt, "FileName");



Hope this works for you !! :) :)

Regards,
Praneet


Hi,

For formatting you will have to create a workbook using interop.

Like this:

1.) Create a sample dt, with new row/ break for a column:

System.Data.DataTable dt = new System.Data.DataTable();
            DataSet ds = new DataSet();
            dt.TableName = "tablename";
            dt.Columns.Add("Code", typeof(string));
            dt.Columns.Add("Price", typeof(int));

            DataRow dr = dt.NewRow();
            dr["Code"] = "ABC " + Environment.NewLine + " qrt";
            dr["Price"] = 12;

            dt.Rows.Add(dr);

            DataRow dr1 = dt.NewRow();
            dr1["Code"] = "PQR";
            dr1["Price"] = 1;

            dt.Rows.Add(dr1);



2.) Create the workbook function using Interop.

public static void CreateWorkbook(System.Data.DataTable dt, String path)
    {
        int rowindex = 0;
        int columnindex = 0;

        Microsoft.Office.Interop.Excel.Application wapp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Worksheet wsheet;
        Microsoft.Office.Interop.Excel.Workbook wbook;

        wapp.Visible = false;

        wbook = wapp.Workbooks.Add(true);
        wsheet = (Worksheet)wbook.ActiveSheet;


        try
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;

            }

            foreach (DataRow row in dt.Rows)
            {
                rowindex++;
                columnindex = 0;
                foreach (DataColumn col in dt.Columns)
                {
                    columnindex++;
                    wsheet.Cells[rowindex + 1, columnindex] = row[col.ColumnName];
                }
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
        }
        wapp.UserControl = true;

        wbook.SaveAs("d:\\Test", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        wbook.Close(null,null,null);



3.) To save the file, call the function like this:

CreateWorkbook(dt,"D:/");



You can apply many formatting types to cells, as per your requirement.
Also, this will save automatically, without user prompt.

Regards,
Praneet


这篇关于我可以自动将Excel文件保存在我的本地文件夹中(不要求任何保存弹出窗口)在C#Asp.Net中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆