我可以将SQL Server表中的数据写入Excel文件并将其保存到我想要的任何地方。我想通过在C:\Format\Sample.xlsx
中读取格式化的Excel文件来升级它,该文件有3张:第一张是我将在第二张中填充数据然后导出的布局。是否可以将数据写入第二张纸,然后保留第一张纸然后导出?
这是我目前的源代码:
clsComboData cdSelectedItem = (clsComboData)cboMatRecv.SelectedItem;
string PhaseNo = cdSelectedItem.ValueData;
string RecvPlanDt = dtpMatRecv.Value.ToString();
string strSQL = null;
string data = null;
int i = 0;
int j = 0;
int ci = 0;
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);
strSQL = "SELECT dbo.M_MAT.*, dbo.RecvPlan.*, dbo.RecvPlan.RecvPlanDt AS Expr1, dbo.RecvPlan.STNO AS Expr2, dbo.M_MAT.MatType AS Expr3 "
+ "FROM dbo.M_MAT INNER JOIN dbo.RecvPlan ON dbo.M_MAT.MatID = dbo.RecvPlan.MatID "
+ "WHERE (dbo.RecvPlan.RecvPlanDt = CONVERT(DATETIME, '" + RecvPlanDt + "', 102)) AND (dbo.RecvPlan.STNO = '"+ PhaseNo + "') AND (dbo.M_MAT.MatType = 0)";
clsCommFunc.gobjdb.SetSql(strSQL);
clsCommFunc.gobjdb.ExecuteReader();
DataSet ds = new DataSet();
clsCommFunc.gobjdb.Fill(ds);
//Header export
for (ci = 0; ci < ds.Tables[0].Columns.Count; ci++)
{
xlWorkSheet.Cells[1, ci + 1] = ds.Tables[0].Columns[ci].ColumnName;
xlWorkSheet.Cells[1, ci + 1].Font.Bold = true;
}
//Data export
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 + 2, j + 1] = data;
}
}
System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
saveDlg.InitialDirectory = @"C:\";
saveDlg.Filter = "Excel files (*.xlsx)|*.xlsx";
saveDlg.FilterIndex = 0;
saveDlg.RestoreDirectory = true;
saveDlg.Title = "Export Excel File To";
if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = saveDlg.FileName;
xlWorkBook.SaveCopyAs(path);
xlWorkBook.Saved = true;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created");