c#操作Exce Sheets.Add 方法怎么用? Worksheet sheet = (Worksheet)WorkBook1.Sheets.get_Item("Sheet1");
WorkBook2.Sheets.Add(sheet,Type.Missing, Type.Missing, Type.Missing)为何总是插入一个空Sheet?请高手指教
WorkBook2.Sheets.Add(sheet,Type.Missing, Type.Missing, Type.Missing)为何总是插入一个空Sheet?请高手指教
public string ExportExcel(Infragistics.Win.UltraWinGrid.UltraGrid grid,string tableName)
{
if (grid.DisplayLayout.ViewStyleBand != Infragistics.Win.UltraWinGrid.ViewStyleBand.Vertical)
return "不支持分组的表格!";
Excel.Application xlApp;
Excel.Workbooks xlBooks;
Excel.Workbook xlBook;
Excel.Sheets xlSheets;
Excel.Worksheet xlSheet;
Excel.Range xlrange;
string strdef = "_TableFormatDef:" + tableName + ":";
SYSCOLUMNSDESCBiz biz = new SYSCOLUMNSDESCBiz();
DataTable dtbl = biz.GetSysPrimaryKey(tableName);
//主键
for (int i = 0; i < dtbl.Rows.Count; i++)
strdef += dtbl.Rows[i]["name"].ToString() + ",";
if (dtbl.Rows.Count > 0)
strdef = strdef.Remove(strdef.Length - 1);
strdef += ":";
//字段
for (int i = 0; i < grid.DisplayLayout.Bands[0].Columns.Count; i++)
strdef += grid.DisplayLayout.Bands[0].Columns[i].Key + ",";
if (strdef.Length > 0)
strdef = strdef.Remove(strdef.Length - 1); xlApp = new Excel.Application();
if (xlApp == null)
{
return "不能启动Excel";
} try
{
xlApp.Visible = false;
xlBooks = xlApp.Workbooks;
xlBook = xlBooks.Add(Missing.Value);
xlSheets = xlBook.Worksheets;
xlSheet = (Excel.Worksheet)xlSheets.get_Item(1);
xlSheet.Name = "数据页";
xlrange = xlSheet.get_Range("B1", Missing.Value);
xlrange.Value2 = "表头名称";
for (int i = 0; i < grid.DisplayLayout.Bands[0].Columns.Count; i++)
xlApp.Cells[2, i + 1] = grid.DisplayLayout.Bands[0].Columns[i].Header.Caption; //第2行为列名定义
xlSheet = (Excel.Worksheet)xlSheets.get_Item(2);
xlSheet.Name = "格式定义";
xlrange = xlSheet.get_Range("A1", Missing.Value);
xlrange.Value2 = strdef; //生成数据
for (int i = 0; i < grid.DisplayLayout.Rows.Count; i++)
for (int j = 0; j < grid.DisplayLayout.Bands[0].Columns.Count; j++)
xlApp.Cells[i+3, j + 1] = grid.DisplayLayout.Rows[i].Cells[j].Text; xlApp.Visible = true;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
//if (xlApp != null)
// Marshal.FinalReleaseComObject(xlApp);
//xlrange = null;
//xlSheet = null;
//xlSheets = null;
//xlBook = null;
//xlBooks = null;
//xlApp = null;
}
return "成功";
}