下面是一个简单的例子,打开一个定义好的
Excel
文件,这个文件是作为报表的模板,然后向模板的指定格子里填充数据,形成一个报表,在
web
方式下可以按照指定的命名方式在服务器上生成一个
excel
文件,之后传送到客户端,由客户端启动
excel
进行打印。
Excel.Application m_objExcel = null;
Excel._Workbook m_objBook = null;
Excel.Sheets m_objSheets = null;
Excel._Worksheet m_objSheet = null;
Excel.Range m_objRange = null;
object
m_objOpt = System.Reflection.Missing.Value;
try
{
m_objExcel = new Excel.Application();
m_objBook = m_objExcel.Workbooks.Open("z://Book1.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
string[] info = new string[5] { "Cure", "26", "dahuzizyd.cnblogs.com", "
汉
"
, "
按时
?
放奥斯丁奥斯丁非是否奥斯丁非
"
};
m_objRange = m_objSheet.get_Range("B1", m_objOpt);
m_objRange.Value = info[0];
m_objRange = m_objSheet.get_Range("E1", m_objOpt);
m_objRange.Value = info[1];
m_objRange = m_objSheet.get_Range("B2", m_objOpt);
m_objRange.Value = info[2];
m_objRange = m_objSheet.get_Range("E2", m_objOpt);
m_objRange.Value = info[3];
m_objRange = m_objSheet.get_Range("A3", m_objOpt);
m_objRange.Value = info[4];
m_objExcel.DisplayAlerts = false;
m_objBook.SaveAs("z://Book2.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);
m_objExcel.Workbooks.Close();
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
m_objBook = null;
m_objExcel = null;
GC.Collect();
}
可以看到,使用
Excel
要进行一部分的编码,好在这部分还不太复杂,但是最大的问题就在于当报表需求变更时,要重新编译部署,而且当格子特别多的时候,要这样硬编码还是挺痛苦的一件事。不过使用
Excel
毕竟给我们提供了一种选择,可以在开发时对多种方案权衡利弊,使用最适合项目的。