public class OfficeAction
{
//网页控件转Excel格式
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
//HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
// string strStyle = "<style>td{mso-number-format:\"\\@\";}</style>";
// tw.WriteLine(strStyle);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
//必须重载后才能导出excel
/*
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
*/
public void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "UTF-8";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
filename = HttpContext.Current.Server.UrlEncode(filename);
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
public void DataTableToExcel(DataTable dt, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "UTF-8";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
filename = HttpContext.Current.Server.UrlEncode(filename);
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
//操作Excel来导出
/*
public void DataTableToExcel(DataTable dt,string filename )
{
string filepath = HttpContext.Current.Server.MapPath(filename);
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks w = xlApp.Workbooks;
Excel.Workbook workbook = w.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
//写入数值
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
}
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
workbook.Saved = true;
workbook.SaveCopyAs(filepath);
xlApp.Quit();
GC.Collect();//强行销毁
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));
HttpContext.Current.Response.WriteFile(filepath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
File.Delete(filepath);
}
*/
//把Excel导入datatable中
public DataTable openExcelToDataTable(string str_path)
{
//string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties=Excel 8.0; "; //第一行为标题列
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties='Excel 8.0;HDR=NO;IMEX=1;'"; //第一行为数据列
try { }
catch
{ }
OleDbConnection ole_cn = new OleDbConnection(strCon);
string[] sheetname = getExcelSheetName(str_path);
bool found = false;
foreach (string strname in sheetname)
{
if (strname == "Sheet1$")
{
found = true;
}
}
string query = "";
if (found)
{
query = "SELECT * FROM [Sheet1$] ";
}
else
{
query = "SELECT * FROM [" + sheetname[0] + "] ";
}
OleDbCommand olecmd = new OleDbCommand(query, ole_cn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(olecmd);
DataTable Excel_tb = new DataTable();
oleAdapter.Fill(Excel_tb);
return Excel_tb;
}
//把Excel导入datatable中
public DataTable openExcelToDataTable(string str_path, string SheetName)
{
// string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties=Excel 8.0; "; //第一行为标题列
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties='Excel 8.0;HDR=NO;IMEX=1;'"; //第一行为数据列
OleDbConnection ole_cn = new OleDbConnection(strCon);
string query = "SELECT * FROM [" + SheetName + "] ";
OleDbCommand olecmd = new OleDbCommand(query, ole_cn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(olecmd);
DataTable Excel_tb = new DataTable();
oleAdapter.Fill(Excel_tb);
return Excel_tb;
}
//取得Excel的Sheet名字
public string[] getExcelSheetName(string str_Path)
{
string excelConnectString = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + str_Path + ";Extended Properties=Excel 8.0";
string excelCom = string.Empty;
OleDbConnection excelConn = new OleDbConnection(excelConnectString);
string[] excelSheetsName ;
try
{
excelConn.Open();
System.Data.DataTable excelDT = null;
excelDT = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheetsName = new String[excelDT.Rows.Count];
int i = 0;
foreach (DataRow row in excelDT.Rows)
{
// 得到表名.
excelSheetsName[i] = row["TABLE_NAME"].ToString();
i++;
}
}
finally
{
excelConn.Close();
}
return excelSheetsName;
}
}
{
//网页控件转Excel格式
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset = "UTF-8";
//HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
// string strStyle = "<style>td{mso-number-format:\"\\@\";}</style>";
// tw.WriteLine(strStyle);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
//必须重载后才能导出excel
/*
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
*/
public void ExportDataSetToExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "UTF-8";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
filename = HttpContext.Current.Server.UrlEncode(filename);
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
public void DataTableToExcel(DataTable dt, string filename)
{
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "UTF-8";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
filename = HttpContext.Current.Server.UrlEncode(filename);
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
//操作Excel来导出
/*
public void DataTableToExcel(DataTable dt,string filename )
{
string filepath = HttpContext.Current.Server.MapPath(filename);
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks w = xlApp.Workbooks;
Excel.Workbook workbook = w.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
//写入字段
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
//写入数值
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
}
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
workbook.Saved = true;
workbook.SaveCopyAs(filepath);
xlApp.Quit();
GC.Collect();//强行销毁
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));
HttpContext.Current.Response.WriteFile(filepath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
File.Delete(filepath);
}
*/
//把Excel导入datatable中
public DataTable openExcelToDataTable(string str_path)
{
//string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties=Excel 8.0; "; //第一行为标题列
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties='Excel 8.0;HDR=NO;IMEX=1;'"; //第一行为数据列
try { }
catch
{ }
OleDbConnection ole_cn = new OleDbConnection(strCon);
string[] sheetname = getExcelSheetName(str_path);
bool found = false;
foreach (string strname in sheetname)
{
if (strname == "Sheet1$")
{
found = true;
}
}
string query = "";
if (found)
{
query = "SELECT * FROM [Sheet1$] ";
}
else
{
query = "SELECT * FROM [" + sheetname[0] + "] ";
}
OleDbCommand olecmd = new OleDbCommand(query, ole_cn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(olecmd);
DataTable Excel_tb = new DataTable();
oleAdapter.Fill(Excel_tb);
return Excel_tb;
}
//把Excel导入datatable中
public DataTable openExcelToDataTable(string str_path, string SheetName)
{
// string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties=Excel 8.0; "; //第一行为标题列
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str_path + ";extended properties='Excel 8.0;HDR=NO;IMEX=1;'"; //第一行为数据列
OleDbConnection ole_cn = new OleDbConnection(strCon);
string query = "SELECT * FROM [" + SheetName + "] ";
OleDbCommand olecmd = new OleDbCommand(query, ole_cn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(olecmd);
DataTable Excel_tb = new DataTable();
oleAdapter.Fill(Excel_tb);
return Excel_tb;
}
//取得Excel的Sheet名字
public string[] getExcelSheetName(string str_Path)
{
string excelConnectString = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + str_Path + ";Extended Properties=Excel 8.0";
string excelCom = string.Empty;
OleDbConnection excelConn = new OleDbConnection(excelConnectString);
string[] excelSheetsName ;
try
{
excelConn.Open();
System.Data.DataTable excelDT = null;
excelDT = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
excelSheetsName = new String[excelDT.Rows.Count];
int i = 0;
foreach (DataRow row in excelDT.Rows)
{
// 得到表名.
excelSheetsName[i] = row["TABLE_NAME"].ToString();
i++;
}
}
finally
{
excelConn.Close();
}
return excelSheetsName;
}
}