日期:2014-05-17  浏览次数:21031 次

C# winform 导成Excel
在windows窗体中,一个界面是有label、textBox、comboBox控件做的,怎么把这个页面上的内容导成Excel的格式,以便保存。

------解决方案--------------------
Excel的格式有很多,2000、2003、2007,你希望导成哪种Excel

当然2007最简单,MS已经有一套很完整的API,好像叫做 Open Document规范。其他版本的Excel你需要找一些非官方dll来帮你,不过容易碰到各种各样的问题。
------解决方案--------------------
Excel.Application objApp = new Excel.Application(); //实例化Excle对象
Excel.Workbooks workbooks = objApp.Workbooks;//实例化工作簿
object missing = Missing.Value;
workbooks.Open(@"D:\票据管理\Mess1.xls", missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);//打开Excle表的模板
Excel.Sheets objSheets = objApp.Worksheets;//实例化sheet工作表的集合
Excel._Worksheet objSheet;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);//导出sheet1模板

//以下是将winform窗体中的控件中的文本值传到Excle表中
objSheet.Cells[2, 2] = "票据" + this.txtNum1.Text + "第" + this.txtNum2.Text + "号";
objSheet.Cells[3, 2] = this.txtdan.Text;
objSheet.Cells[4, 2] = this.txtdi.Text;
objSheet.Cells[5, 2] = this.txtren.Text;
objSheet.Cells[5, 4] = this.txtdan.Text;
objSheet.Cells[5, 6] = this.txtzhu.Text;
objSheet.Cells[5, 8] = this.txtyu.Text;
objSheet.Cells[4, 6] = this.txthang.Text;
objSheet.Cells[4, 8] = this.txtyou.Text.Trim();
//objSheet.Cells[4, 8] = this.textBox1.Text;
objSheet.Cells[7, 1] = "统计区间:" + this.dtpDa.Text + "至" + this.dtpDb.Text;

//将DataGridView中的数据导入到Excel中
for (int i = 0; i < this.dataGridView2.RowCount; i++)
{
objApp.Cells[9 + i, 1] = dataGridView2["GetDate", i].Value;
objApp.Cells[9 + i, 2] = dataGridView2["PurchaseQuantity", i].Value;
objApp.Cells[9 + i, 3] = dataGridView2["TrueQuantity", i].Value;
objApp.Cells[9 + i, 4] = dataGridView2["BeginNum", i].Value;
objApp.Cells[9 + i, 5] = dataGridView2["EndNum", i].Value;
objApp.Cells[9 + i, 6] = "'" + dataGridView2["Remark", i].Value;

}
objApp.Visible = true;
objApp.DisplayAlerts = false;

------解决方案--------------------
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";

DateTime now = DateTime.Now;
saveFileDialog.FileName = now.Year.ToString().PadLeft(2)
+ now.Month.ToString().PadLeft(2, '0')
+ now.Day.ToString().PadLeft(2, '0') + "-"
+ now.Hour.ToString().PadLeft(2, '0')
+ now.Minute.ToString().PadLeft(2, '0')
+ now.Second.ToString().PadLeft(2, '0');

saveFileDialog.ShowDialog();

Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}

sw.WriteLine(str);
//写内容