数据导出只导出当前页的,不能导出全部数据。
代码如下:
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("表格中无数据导出");
return;
}
SaveFileDialog dlg = new SaveFileDialog();
if (this.ckTXT.Checked)
{
dlg.Filter = "Text files (*.txt)|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
Stream myStream = dlg.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string strTitle = "";
//生成字段名称
for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
{
strTitle += dataGridView1.Columns[i].HeaderText.ToString() + ",";
}
sw.WriteLine(strTitle.Substring(0, strTitle.Length - 1));
//写内容
string tempStr = "";
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
for (int k = 0; k < this.dataGridView1.Columns.Count; k++)
{
tempStr += this.dataGridView1.Rows[j].Cells[k].Value.ToString() + ",";
}
sw.WriteLine(tempStr.Substring(0, tempStr.Length - 1));
tempStr = "";
}
sw.Close();
myStream.Close();
MessageBox.Show("数据导出完成", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//add by liuguichao@20110513
else if (this.ckExcel.Checked)
{
dlg.Filter = "Excel文件 (*.xls)|*.xls";
if (dlg.ShowDialog() == DialogResult.OK)
{
ExcelWriter writer = new ExcelWriter(dlg.FileName, "安徽边坡数据");
string[] header = new string[dataGridView1.Columns.Count];
Type[] colType = new Type[dataGridView1.Columns.Count];
//生成字段名称
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
header[i] = dataGridView1.Columns[i].HeaderText.ToString();
colType[i] = typeof(System.String);
}
writer.WriteHeaderLine(header, colType);
string[] dataLine = new string[dataGridView1.Columns.Count];
for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < this.dataGridView1.Columns.Count; j++)
{
dataLine[j] = this.dataGridView1.Rows[i].Cells[j].Value.ToString();
}
writer.WriteDataLine(dataLine);
}
writer.Save();
MessageBox.Show("数据导出完成", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);