/*利用流技术,将控件中的数据经过文件流导入到excel中*/编码
private void toolStripbtnSave_Click(object sender, EventArgs e)excel
{ //将数据表中的数据保存到excel文件中 SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "txt files (*.txt)|*.txt|excel files (*.xls)|*.xls|All files (*.*)|*.*"; dlg.FilterIndex = 2; dlg.Title = "存盘设置"; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; //dlg.ShowDialog(); Stream myStream; if (dlg.ShowDialog() == DialogResult.OK) { if ((myStream = dlg.OpenFile()) != null) { if (dlg.FilterIndex == 2) { //保存数据 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0)); //利用系统默认编码格式,将字符写入到文件流中。 string columnTitle = ""; //写入列标题 for (int i = 0; i < mtrData.ColumnCount; i++) { if (i > 0) { columnTitle += "\t"; } columnTitle += mtrData.Columns[i].HeaderText; } sw.WriteLine(columnTitle); //写入列内容 for (int i = 0; i < mtrData.RowCount; i++) { string columnValue = ""; for (int j = 0; j < mtrData.ColumnCount; j++) { if (j > 0) { columnValue += "\t"; } if (mtrData.Rows[i].Cells[j].Value == null) columnValue += ""; else columnValue += mtrData.Rows[i].Cells[j].Value.ToString().Trim(); } sw.WriteLine(columnValue); } sw.Close(); } myStream.Close(); } } }