엑셀 조작 방법
15403 단어 Excel
첫 번 째: html 코드 를 직접 인쇄 한 다음 에 출력 형식 을 엑셀 파일 로 위장 합 니 다 (엑셀 은 xml 과 html 코드 를 식별 할 수 있 습 니 다)
코드 예시:
/// <summary>
/// html excel
/// : , 、
/// : excel excel , 。 html
/// : excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtnHtml_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("HtmlExcel.xls", Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";
PageInfo<VW_CLN_LendAfter_CustDetail> PageToPtint = ViewEntitiy.VW_CLN_LendAfter_CustDetail.Query(0, 15, "select * from VW_CLN_LendAfter_CustDetail where 1=1 ", ToList);
DataSoucre = (DataSet)PageToPtint.DataList;
DataTable dt = DataSoucre.Tables[0];
foreach(string key in TotableDC.Keys)
{
if (dt.Columns.Contains(key))
{
dt.Columns[key].ColumnName = TotableDC[key];
}
}
StringBuilder strexcel = new StringBuilder();
strexcel.Append(@"<table><tr>");
//
foreach(DataColumn dc in dt.Columns)
{
if (TotableDC.Values.Contains(dc.ColumnName))
{
strexcel.Append(@"<th>" + dc.ColumnName + "</th>");
}
}
strexcel.Append(@"</tr>");
//
foreach (System.Data.DataRow dr in dt.Rows)
{
strexcel.Append(@"<tr>");
foreach(System.Data.DataColumn dc in dt.Columns)
{
if (TotableDC.Values.Contains(dc.ColumnName))
{
strexcel.Append(@"<td>" + dr[dc.ColumnName] + @"</td>");
}
}
strexcel.Append(@"</tr>");
}
strexcel.Append(@"<table>");
Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>" + strexcel);
Response.End();
}
두 번 째: Appliction 으로 엑셀 내 보 내기 여기 서 말 하 는 Applcation 은 마이크로소프트 가 제공 하 는 OFFICE DOM 구성 요소 입 니 다.이런 장점 과 결점 은 모두 매우 뚜렷 하 다.
코드 예제:
/// <summary>
/// Appliction excel
/// : , Excel
/// : excel ,IIS , , ,
/// : excel ,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtnApplication_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("HtmlExcel.xlsx", Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";
System.IO.FileInfo FileInfo = new System.IO.FileInfo(Server.MapPath("b .XLS"));
if (FileInfo.Exists) { FileInfo.Delete(); }
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); ;
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); ;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
Microsoft.Office.Interop.Excel.Range ExcelRange;
try
{
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
PageInfo<VW_CLN_LendAfter_CustDetail> PageToPtint = ViewEntitiy.VW_CLN_LendAfter_CustDetail.Query(0, 15, "select * from VW_CLN_LendAfter_CustDetail where 1=1 ", ToList);
DataSoucre = (DataSet)PageToPtint.DataList;
DataTable dt = DataSoucre.Tables[0];
int intcolums = 0;
foreach (string key in TotableDC.Keys)
{
if (dt.Columns.Contains(key))
{
dt.Columns[key].ColumnName = TotableDC[key];
}
}
//
foreach (DataColumn dc in dt.Columns)
{
if (TotableDC.Values.Contains(dc.ColumnName))
{
// Range excel A 1 Z
string rangename = (Char)(intcolums + 65) + "1";
//worksheet.Range[rangename] worksheet.Range["A1","G5"] A1 G5
ExcelRange = worksheet.Range[rangename];
ExcelRange.Value = dc.ColumnName;
intcolums += 1;
}
}
//
int introw = 2;
foreach (System.Data.DataRow dr in dt.Rows)
{
intcolums = 0;
foreach (System.Data.DataColumn dc in dt.Columns)
{
if (TotableDC.Values.Contains(dc.ColumnName))
{
string rangename = (Char)(intcolums + 65) + introw.ToString();
ExcelRange = worksheet.Range[rangename];
ExcelRange.NumberFormat = "@";
ExcelRange.Value = dr[dc.ColumnName];
intcolums += 1;
}
}
introw += 1;
}
workbook.Saved = true;
workbook.SaveAs(Server.MapPath( "b .XLS"));
}
catch(Exception ex)
{
}
finally
{
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlApp.Quit();
xlApp = null;
}
Response.WriteFile(Server.MapPath( "b .XLS"));
Response.End();
}
세 번 째: ADO. NET 을 사용 하여 sql 링크 를 진행 합 니 다.
/// <summary>
/// ADO.NET '
/// : ,
/// : , , , ,
/// : word ,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtnString_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("HtmlExcel.xlsx", Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";
PageInfo<VW_CLN_LendAfter_CustDetail> PageToPtint = ViewEntitiy.VW_CLN_LendAfter_CustDetail.Query(0, 15, "select * from VW_CLN_LendAfter_CustDetail where 1=1 ", ToList);
DataSoucre = (DataSet)PageToPtint.DataList;
DataSet DS=new DataSet();
DataTable dt = DataSoucre.Tables[0].Copy();
DS.Tables.Add(dt);
foreach (string key in TotableDC.Keys)
{
if (dt.Columns.Contains(key))
{
dt.Columns[key].ColumnName = TotableDC[key];
}
}
FileInfo ModelInfo = new System.IO.FileInfo(Server.MapPath("Model.xlsx"));
FileInfo FileInfo = new System.IO.FileInfo(Server.MapPath(DateTime.Now.ToString("yyyyMMdd")+".xlsx"));
if (FileInfo.Exists)
{
FileInfo.Delete();
}
ModelInfo.CopyTo(Server.MapPath(DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
DataSoucre.Tables[0].TableName = "Biao";
DSToExcel2007(Server.MapPath(DateTime.Now.ToString("yyyyMMdd") + ".xlsx"), DS, DataSoucre.Tables[0].TableName);
Response.WriteFile(Server.MapPath((DateTime.Now.ToString("yyyyMMdd") + ".xlsx")));
Response.End();
}
/// <summary>
/// Excel
/// </summary>
/// <param name="Path"> Excel </param>
/// <param name="oldds"> </param>
/// <param name="TableName"> </param>
public static void DSToExcel2007(string Path, DataSet oldds, string TableName)
{
//Excel2007
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Path + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=0;ReadOnly=False \"";
//
ExcuteSQL(oldds, TableName, strConn);
}
/// <summary>
///
/// </summary>
/// <param name="oldds"> </param>
/// <param name="TableName"> </param>
/// <param name="strCon"> </param>
private static void ExcuteSQL(DataSet oldds, string TableName, string strCon)
{
//
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "select * from [" + TableName + "$]";
try
{
//string CreateTable = "";
//foreach (System.Data.DataColumn dc in ndt.Columns)
//{
// CreateTable += "ALTER table [" + TableName + "] add [" + dc.ColumnName + "] Text ";
// OleDbCommand cmd = new OleDbCommand(CreateTable, myConn);
// cmd.ExecuteNonQuery();
//}
////CreateTable = CreateTable.Trim(',');
////CreateTable += ")";
////OleDbCommand cmd = new OleDbCommand(CreateTable, myConn);
//// cmd.ExecuteNonQuery();
//System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
System.Data.DataTable ndt = oldds.Tables[0].Clone();
string CreateTable = "create table [" + TableName + "](";
foreach (System.Data.DataColumn dc in ndt.Columns)
{
CreateTable += "["+dc.ColumnName+"] Text,";
}
CreateTable = CreateTable.Trim(',');
CreateTable += ")";
OleDbCommand cmd = new OleDbCommand(CreateTable, myConn);
cmd.ExecuteNonQuery();
string DelteTable = " drop table [Sheet1]";
System.Data.OleDb.OleDbCommandBuilder builder = new OleDbCommandBuilder(myCommand);
//QuotePrefix QuoteSuffix builder InsertComment 。
// insert ( )
builder.QuotePrefix = "[";
// insert ( )
builder.QuoteSuffix = "]";
DataSet newds = new DataSet();
//
//
//ndt.Rows.Clear();
ndt.TableName = TableName;
newds.Tables.Add(ndt);
for (int i = 0; i < oldds.Tables[0].Rows.Count; i++)
{
// ImportRow news ,
// ImportRow DataRow (DataRowState )。
// ImportRow newds , Excel DataRowState!=Added
DataRow nrow = newds.Tables[0].NewRow();
for (int j = 0; j < oldds.Tables[0].Columns.Count; j++)
{
nrow[j] = oldds.Tables[0].Rows[i][j];
}
newds.Tables[0].Rows.Add(nrow);
}
//DataTable dt = oldds.Tables[1];
//
myCommand.Update(newds, TableName);
}
finally
{
myConn.Close();
}
}
네 번 째, 제3자 구성 요 소 를 사용 합 니 다. 제3자 구성 요 소 는 여러 가지 가 있 습 니 다. 제 가 사용 하 는 것 은 aspose. cell 구성 요소 입 니 다.
코드 예제:
/// <summary>
/// Aspose excel
/// : , , , ,
/// : , , .net
/// : .net4.0 , .net 3.5 ,3.5
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void BtnAspose_Click(object sender, EventArgs e)
{
Aspose.Cells.Workbook Worbook = new Aspose.Cells.Workbook("b .XLS");
Worksheet sheet = Worbook.Worksheets[0];
Cells cell = sheet.Cells;
PageInfo<VW_CLN_LendAfter_CustDetail> PageToPtint = ViewEntitiy.VW_CLN_LendAfter_CustDetail.Query(0, 15, "select * from VW_CLN_LendAfter_CustDetail where 1=1 ", ToList);
DataSoucre = (DataSet)PageToPtint.DataList;
DataTable dt = DataSoucre.Tables[0].Copy();
foreach (string key in TotableDC.Keys)
{
if (dt.Columns.Contains(key))
{
dt.Columns[key].ColumnName = TotableDC[key];
}
}
// Aspose.CELLS F12
// dt 0 0 Word , TRUE
cell.ImportDataTable(dt, true, 0, 0);
// , xls xlsx
XlsSaveOptions saveOptions = new XlsSaveOptions() ;
saveOptions.SaveFormat = SaveFormat.Xlsx;
// Worbook.Save(Response, SaveFormat.Xlsx, ContentDisposition.Attachment, new SaveOptions(){ SaveType = SaveType.OpenInExcel, SaveFormat=SaveFormat.Xlsx, ClearData=true, CachedFileFolder="AsposeExcel.xlsx"});
// Worbook.Save(@ )
Worbook.Save(Response,"BaoBiao.xlsx", ContentDisposition.Attachment,saveOptions);
//Aspose
// cell[0,1]
// cell[0,1].Value=" "
// cell[0,1].SetStyle( new Aspose.Cells.Style(){ VerticalAlignment=TextAlignmentType.Center} ); cell[0,1].GetStyle()
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Excel Grep toolExcel Grep tool ■히나가타 ■ 시트 구성 ExcelGrep.cls...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.