c#怎么输出Excel

2025-01-07 05:01:15
推荐回答(3个)
回答1:

//创建Excel对象
Application excel = new Application();
//设置表的个数
excel.SheetsInNewWorkbook = 2;
excel.SaveWorkspace("E:\\");
//创建WorkBook
excel.Workbooks.Add();
//第一个工作表
Worksheet sheet1 =(Worksheet)excel.ActiveWorkbook.Worksheets[1];
sheet1.Name = ".NET";
sheet1.Cells[1, 1] = "欢迎来到.NET";

//第2个工作表
Worksheet sheet2 = (Worksheet)excel.ActiveWorkbook.Worksheets[2];
sheet2.Name = "ASP.NET";
sheet2.Cells[1, 1] = "欢迎来到.NET";
//显示Excel
excel.Visible = true; 这是一个EXCEL导出步骤

回答2:

try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0; if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Export Excel File To";
string strName = saveFileDialog.FileName; Missing miss = Missing.Value;
Excel.Application excel = new Excel.ApplicationClass();
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook book = books.Add(miss);
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
sheet.Name = "test"; int colIndex = 0;
int rowIndex = 1; foreach (DataColumn col in MyDataTable.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
foreach (DataRow row in MyDataTable.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in MyDataTable.Columns)
{
colIndex++;
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
excel.get_Range(excel.Cells[1, colIndex], excel.Cells[1, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
excel.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
}
}
sheet.SaveAs(strName, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
book.Close(true, miss, miss);
books.Close();
excel.Quit();
MessageBox.Show("导出成功!");
}
}
catch
{
MessageBox.Show("导出失败!");
}

回答3:

你留下email,我发给你吧