C#的后台,如何导出EXCEL
发布网友
发布时间:2022-04-25 21:56
我来回答
共1个回答
热心网友
时间:2022-06-17 21:41
C#把查询出来的数据导出到Excel代码的代码如下:
1、创建form
public Form1()
{
InitializeComponent();
}
2、点击button开始查询db并导入excel数据
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn ; //sql连接对象
string connectionString = null; 数据库连接串
string sql = null; 执行sql定义
string data = null; 初始化结果
int i = 0;
int j = 0;
//以下是声明并创建excel文件
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//开始连接数据库
connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
cnn = new SqlConnection(connectionString);
cnn.Open(); //打开数据库
sql = "SELECT * FROM Proct"; //定义查询sql语句
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); //执行查询
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//数据导入到excel文件
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
}